blob: 6ee94b51eed20ec10977319d90ea16b21581c378 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Gregory P. Smithaafdca82010-01-04 04:50:36 +00007import io
Barry Warsawcf3d4b51997-01-03 20:03:32 +00008import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import select
Christian Heimesbbe741d2008-03-28 10:53:29 +000010import time
11import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000012import queue
Jack Jansen522e7692002-09-06 21:57:50 +000013import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000014import os
15import array
Antoine Pitrouacd0fda2010-10-23 17:01:44 +000016import platform
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +000017import contextlib
Raymond Hettinger027bb632004-05-31 03:09:25 +000018from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import signal
Antoine Pitrou6d7df632010-09-27 17:52:25 +000020import math
Antoine Pitrou6d58d642011-03-20 23:56:36 +010021import pickle
Antoine Pitroub1c54962010-10-14 15:05:38 +000022try:
23 import fcntl
24except ImportError:
25 fcntl = False
Barry Warsawcf3d4b51997-01-03 20:03:32 +000026
Giampaolo Rodolà419f7042010-08-14 16:45:41 +000027def try_address(host, port=0, family=socket.AF_INET):
28 """Try to bind a socket on the given host:port and return True
29 if that has been possible."""
30 try:
31 sock = socket.socket(family, socket.SOCK_STREAM)
32 sock.bind((host, port))
33 except (socket.error, socket.gaierror):
34 return False
35 else:
36 sock.close()
37 return True
38
Antoine Pitrou1cae8b52010-10-23 17:05:13 +000039def linux_version():
40 try:
41 # platform.release() is something like '2.6.33.7-desktop-2mnb'
42 version_string = platform.release().split('-')[0]
43 return tuple(map(int, version_string.split('.')))
44 except ValueError:
45 return 0, 0, 0
46
Benjamin Petersonee8712c2008-05-20 21:35:26 +000047HOST = support.HOST
Marc-André Lemburg8f36af72011-02-25 15:42:01 +000048MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
Giampaolo Rodolà419f7042010-08-14 16:45:41 +000049SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000050
Victor Stinner45df8202010-04-28 22:31:17 +000051try:
52 import _thread as thread
53 import threading
54except ImportError:
55 thread = None
56 threading = None
57
Guido van Rossum24e4af82002-06-12 19:18:08 +000058class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000059
Guido van Rossum24e4af82002-06-12 19:18:08 +000060 def setUp(self):
61 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000062 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000063 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000064
Guido van Rossum24e4af82002-06-12 19:18:08 +000065 def tearDown(self):
66 self.serv.close()
67 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000068
Guido van Rossum24e4af82002-06-12 19:18:08 +000069class SocketUDPTest(unittest.TestCase):
70
71 def setUp(self):
72 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000073 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000074
75 def tearDown(self):
76 self.serv.close()
77 self.serv = None
78
79class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000080 """Threadable Test class
81
82 The ThreadableTest class makes it easy to create a threaded
83 client/server pair from an existing unit test. To create a
84 new threaded class from an existing unit test, use multiple
85 inheritance:
86
87 class NewClass (OldClass, ThreadableTest):
88 pass
89
90 This class defines two new fixture functions with obvious
91 purposes for overriding:
92
93 clientSetUp ()
94 clientTearDown ()
95
96 Any new test functions within the class must then define
97 tests in pairs, where the test name is preceeded with a
98 '_' to indicate the client portion of the test. Ex:
99
100 def testFoo(self):
101 # Server portion
102
103 def _testFoo(self):
104 # Client portion
105
106 Any exceptions raised by the clients during their tests
107 are caught and transferred to the main thread to alert
108 the testing framework.
109
110 Note, the server setup function cannot call any blocking
111 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000113 the blocking call (such as in setting up a client/server
114 connection and performing the accept() in setUp().
115 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116
117 def __init__(self):
118 # Swap the true setup function
119 self.__setUp = self.setUp
120 self.__tearDown = self.tearDown
121 self.setUp = self._setUp
122 self.tearDown = self._tearDown
123
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000124 def serverExplicitReady(self):
125 """This method allows the server to explicitly indicate that
126 it wants the client thread to proceed. This is useful if the
127 server is about to execute a blocking routine that is
128 dependent upon the client thread during its setup routine."""
129 self.server_ready.set()
130
Guido van Rossum24e4af82002-06-12 19:18:08 +0000131 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000132 self.server_ready = threading.Event()
133 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000134 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000135 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000136
137 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000138 methodname = self.id()
139 i = methodname.rfind('.')
140 methodname = methodname[i+1:]
141 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000142 self.client_thread = thread.start_new_thread(
143 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000144
145 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000146 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000147 self.server_ready.set()
148 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000149
150 def _tearDown(self):
151 self.__tearDown()
152 self.done.wait()
153
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000154 if self.queue.qsize():
Antoine Pitrou98b46702010-09-18 22:59:00 +0000155 exc = self.queue.get()
156 raise exc
Guido van Rossum24e4af82002-06-12 19:18:08 +0000157
158 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000159 self.server_ready.wait()
160 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000161 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000162 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000163 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000164 try:
165 test_func()
Antoine Pitrou98b46702010-09-18 22:59:00 +0000166 except BaseException as e:
167 self.queue.put(e)
168 finally:
169 self.clientTearDown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000170
171 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000172 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000173
174 def clientTearDown(self):
175 self.done.set()
176 thread.exit()
177
178class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
179
180 def __init__(self, methodName='runTest'):
181 SocketTCPTest.__init__(self, methodName=methodName)
182 ThreadableTest.__init__(self)
183
184 def clientSetUp(self):
185 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
186
187 def clientTearDown(self):
188 self.cli.close()
189 self.cli = None
190 ThreadableTest.clientTearDown(self)
191
192class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
193
194 def __init__(self, methodName='runTest'):
195 SocketUDPTest.__init__(self, methodName=methodName)
196 ThreadableTest.__init__(self)
197
198 def clientSetUp(self):
199 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
200
Brian Curtin3beb38f2010-11-04 03:41:43 +0000201 def clientTearDown(self):
202 self.cli.close()
203 self.cli = None
204 ThreadableTest.clientTearDown(self)
205
Guido van Rossum24e4af82002-06-12 19:18:08 +0000206class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000207 """Socket tests for client-server connection.
208
209 self.cli_conn is a client socket connected to the server. The
210 setUp() method guarantees that it is connected to the server.
211 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000212
213 def __init__(self, methodName='runTest'):
214 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
215
216 def setUp(self):
217 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000218 # Indicate explicitly we're ready for the client thread to
219 # proceed and then perform the blocking call to accept
220 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000221 conn, addr = self.serv.accept()
222 self.cli_conn = conn
223
224 def tearDown(self):
225 self.cli_conn.close()
226 self.cli_conn = None
227 ThreadedTCPSocketTest.tearDown(self)
228
229 def clientSetUp(self):
230 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000231 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000232 self.serv_conn = self.cli
233
234 def clientTearDown(self):
235 self.serv_conn.close()
236 self.serv_conn = None
237 ThreadedTCPSocketTest.clientTearDown(self)
238
Dave Cole331708b2004-08-09 04:51:41 +0000239class SocketPairTest(unittest.TestCase, ThreadableTest):
240
241 def __init__(self, methodName='runTest'):
242 unittest.TestCase.__init__(self, methodName=methodName)
243 ThreadableTest.__init__(self)
244
245 def setUp(self):
246 self.serv, self.cli = socket.socketpair()
247
248 def tearDown(self):
249 self.serv.close()
250 self.serv = None
251
252 def clientSetUp(self):
253 pass
254
255 def clientTearDown(self):
256 self.cli.close()
257 self.cli = None
258 ThreadableTest.clientTearDown(self)
259
Tim Peters494aaee2004-08-09 18:54:11 +0000260
Guido van Rossum24e4af82002-06-12 19:18:08 +0000261#######################################################################
262## Begin Tests
263
264class GeneralModuleTests(unittest.TestCase):
265
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000266 def test_repr(self):
267 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000268 self.addCleanup(s.close)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000270
Raymond Hettinger027bb632004-05-31 03:09:25 +0000271 def test_weakref(self):
272 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
273 p = proxy(s)
274 self.assertEqual(p.fileno(), s.fileno())
275 s.close()
276 s = None
277 try:
278 p.fileno()
279 except ReferenceError:
280 pass
281 else:
282 self.fail('Socket proxy still exists')
283
Guido van Rossum24e4af82002-06-12 19:18:08 +0000284 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000285 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000286 def raise_error(*args, **kwargs):
287 raise socket.error
288 def raise_herror(*args, **kwargs):
289 raise socket.herror
290 def raise_gaierror(*args, **kwargs):
291 raise socket.gaierror
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000292 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000293 "Error raising socket exception.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000294 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000295 "Error raising socket exception.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000296 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000297 "Error raising socket exception.")
298
299 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000300 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000301 socket.AF_INET
302 socket.SOCK_STREAM
303 socket.SOCK_DGRAM
304 socket.SOCK_RAW
305 socket.SOCK_RDM
306 socket.SOCK_SEQPACKET
307 socket.SOL_SOCKET
308 socket.SO_REUSEADDR
309
Guido van Rossum654c11e2002-06-13 20:24:17 +0000310 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000311 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000312 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000313 try:
314 ip = socket.gethostbyname(hostname)
315 except socket.error:
316 # Probably name lookup wasn't set up right; skip this test
317 return
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000318 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000319 try:
320 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
321 except socket.error:
322 # Probably a similar problem as above; skip this test
323 return
Brett Cannon01668a12005-03-11 00:04:17 +0000324 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000325 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000326 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000328
Antoine Pitrou061cfb52011-02-28 22:25:22 +0000329 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
330 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
331 def test_sethostname(self):
332 oldhn = socket.gethostname()
333 try:
334 socket.sethostname('new')
335 except socket.error as e:
336 if e.errno == errno.EPERM:
337 self.skipTest("test should be run as root")
338 else:
339 raise
340 try:
341 # running test as root!
342 self.assertEqual(socket.gethostname(), 'new')
343 # Should work with bytes objects too
344 socket.sethostname(b'bar')
345 self.assertEqual(socket.gethostname(), 'bar')
346 finally:
347 socket.sethostname(oldhn)
348
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000349 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000350 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000351 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000352 try:
353 # On some versions, this loses a reference
354 orig = sys.getrefcount(__name__)
355 socket.getnameinfo(__name__,0)
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000356 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000357 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000358 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000359
Guido van Rossum24e4af82002-06-12 19:18:08 +0000360 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000361 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000362 try:
363 # On some versions, this crashes the interpreter.
364 socket.getnameinfo(('x', 0, 0, 0), 0)
365 except socket.error:
366 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000367
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000368 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000369 # This just checks that htons etc. are their own inverse,
370 # when looking at the lower 16 or 32 bits.
371 sizes = {socket.htonl: 32, socket.ntohl: 32,
372 socket.htons: 16, socket.ntohs: 16}
373 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000374 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000375 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
376 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000377
Guido van Rossuma2627af2002-09-14 00:58:46 +0000378 swapped = func(mask)
379 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000380 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000381
Guido van Rossum018919a2007-01-15 00:07:32 +0000382 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000383 good_values = [ 1, 2, 3, 1, 2, 3 ]
384 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000385 for k in good_values:
386 socket.ntohl(k)
387 socket.ntohs(k)
388 socket.htonl(k)
389 socket.htons(k)
390 for k in bad_values:
391 self.assertRaises(OverflowError, socket.ntohl, k)
392 self.assertRaises(OverflowError, socket.ntohs, k)
393 self.assertRaises(OverflowError, socket.htonl, k)
394 self.assertRaises(OverflowError, socket.htons, k)
395
Barry Warsaw11b91a02004-06-28 00:50:43 +0000396 def testGetServBy(self):
397 eq = self.assertEqual
398 # Find one service that exists, then check all the related interfaces.
399 # I've ordered this by protocols that have both a tcp and udp
400 # protocol, at least for modern Linuxes.
Gregory P. Smithb603d032010-10-17 00:17:24 +0000401 if (sys.platform.startswith('linux') or
402 sys.platform.startswith('freebsd') or
403 sys.platform.startswith('netbsd') or
404 sys.platform == 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000405 # avoid the 'echo' service on this platform, as there is an
406 # assumption breaking non-standard port/protocol entry
407 services = ('daytime', 'qotd', 'domain')
408 else:
409 services = ('echo', 'daytime', 'domain')
410 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000411 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000412 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000413 break
414 except socket.error:
415 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000416 else:
417 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000418 # Try same call with optional protocol omitted
419 port2 = socket.getservbyname(service)
420 eq(port, port2)
421 # Try udp, but don't barf it it doesn't exist
422 try:
423 udpport = socket.getservbyname(service, 'udp')
424 except socket.error:
425 udpport = None
426 else:
427 eq(udpport, port)
428 # Now make sure the lookup by port returns the same service name
429 eq(socket.getservbyport(port2), service)
430 eq(socket.getservbyport(port, 'tcp'), service)
431 if udpport is not None:
432 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000433 # Make sure getservbyport does not accept out of range ports.
434 self.assertRaises(OverflowError, socket.getservbyport, -1)
435 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000436
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000437 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000438 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000439 # The default timeout should initially be None
440 self.assertEqual(socket.getdefaulttimeout(), None)
441 s = socket.socket()
442 self.assertEqual(s.gettimeout(), None)
443 s.close()
444
445 # Set the default timeout to 10, and see if it propagates
446 socket.setdefaulttimeout(10)
447 self.assertEqual(socket.getdefaulttimeout(), 10)
448 s = socket.socket()
449 self.assertEqual(s.gettimeout(), 10)
450 s.close()
451
452 # Reset the default timeout to None, and see if it propagates
453 socket.setdefaulttimeout(None)
454 self.assertEqual(socket.getdefaulttimeout(), None)
455 s = socket.socket()
456 self.assertEqual(s.gettimeout(), None)
457 s.close()
458
459 # Check that setting it to an invalid value raises ValueError
460 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
461
462 # Check that setting it to an invalid type raises TypeError
463 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
464
Benjamin Petersonf91df042009-02-13 02:50:59 +0000465 def testIPv4_inet_aton_fourbytes(self):
466 if not hasattr(socket, 'inet_aton'):
467 return # No inet_aton, nothing to check
468 # Test that issue1008086 and issue767150 are fixed.
469 # It must return 4 bytes.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000470 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
471 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
Benjamin Petersonf91df042009-02-13 02:50:59 +0000472
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000473 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000474 if not hasattr(socket, 'inet_pton'):
475 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000476 from socket import inet_aton as f, inet_pton, AF_INET
477 g = lambda a: inet_pton(AF_INET, a)
478
Ezio Melottib3aedd42010-11-20 19:04:17 +0000479 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
480 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
481 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
482 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
483 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000484
Ezio Melottib3aedd42010-11-20 19:04:17 +0000485 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
486 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
487 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
488 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000489
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000490 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000491 if not hasattr(socket, 'inet_pton'):
492 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000493 try:
494 from socket import inet_pton, AF_INET6, has_ipv6
495 if not has_ipv6:
496 return
497 except ImportError:
498 return
499 f = lambda a: inet_pton(AF_INET6, a)
500
Ezio Melottib3aedd42010-11-20 19:04:17 +0000501 self.assertEqual(b'\x00' * 16, f('::'))
502 self.assertEqual(b'\x00' * 16, f('0::0'))
503 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
504 self.assertEqual(
Guido van Rossum67180622007-07-10 07:29:12 +0000505 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 +0000506 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
507 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000508
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000509 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000510 if not hasattr(socket, 'inet_ntop'):
511 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000512 from socket import inet_ntoa as f, inet_ntop, AF_INET
513 g = lambda a: inet_ntop(AF_INET, a)
514
Ezio Melottib3aedd42010-11-20 19:04:17 +0000515 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
516 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
517 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
518 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000519
Ezio Melottib3aedd42010-11-20 19:04:17 +0000520 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
521 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
522 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000523
524 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000525 if not hasattr(socket, 'inet_ntop'):
526 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000527 try:
528 from socket import inet_ntop, AF_INET6, has_ipv6
529 if not has_ipv6:
530 return
531 except ImportError:
532 return
533 f = lambda a: inet_ntop(AF_INET6, a)
534
Ezio Melottib3aedd42010-11-20 19:04:17 +0000535 self.assertEqual('::', f(b'\x00' * 16))
536 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
537 self.assertEqual(
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000538 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000539 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 +0000540 )
541
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000542 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000543
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000544 def _get_unused_port(self, bind_address='0.0.0.0'):
545 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000546
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000547 Args:
548 bind_address: Hostname or IP address to search for a port on.
549
550 Returns: A most likely to be unused port.
551 """
552 tempsock = socket.socket()
553 tempsock.bind((bind_address, 0))
554 host, port = tempsock.getsockname()
555 tempsock.close()
556 return port
557
558 def testSockName(self):
559 # Testing getsockname()
560 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000561 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000562 self.addCleanup(sock.close)
Christian Heimes5e696852008-04-09 08:37:03 +0000563 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000564 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
566 # it reasonable to get the host's addr in addition to 0.0.0.0.
567 # At least for eCos. This is required for the S/390 to pass.
Georg Brandl89197fe2010-11-20 14:16:17 +0000568 try:
569 my_ip_addr = socket.gethostbyname(socket.gethostname())
570 except socket.error:
571 # Probably name lookup wasn't set up right; skip this test
572 return
Benjamin Peterson577473f2010-01-19 00:09:57 +0000573 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000574 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000575
576 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000577 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000578 # We know a socket should start without reuse==0
579 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000580 self.addCleanup(sock.close)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000581 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000582 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000583
584 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000585 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000586 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000587 self.addCleanup(sock.close)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000588 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
589 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000590 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000591
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000592 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000593 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000594 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
595 sock.settimeout(1)
596 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000597 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000599 def testNewAttributes(self):
600 # testing .family, .type and .protocol
601 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
602 self.assertEqual(sock.family, socket.AF_INET)
603 self.assertEqual(sock.type, socket.SOCK_STREAM)
604 self.assertEqual(sock.proto, 0)
605 sock.close()
606
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000607 def test_getsockaddrarg(self):
608 host = '0.0.0.0'
609 port = self._get_unused_port(bind_address=host)
610 big_port = port + 65536
611 neg_port = port - 65536
612 sock = socket.socket()
613 try:
614 self.assertRaises(OverflowError, sock.bind, (host, big_port))
615 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
616 sock.bind((host, port))
617 finally:
618 sock.close()
619
Brian Curtin5ad0bd62010-11-05 15:47:45 +0000620 @unittest.skipUnless(os.name == "nt", "Windows specific")
Christian Heimesfaf2f632008-01-06 16:59:19 +0000621 def test_sock_ioctl(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000622 self.assertTrue(hasattr(socket.socket, 'ioctl'))
623 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
624 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
625 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Kristján Valur Jónsson847ec752009-09-27 21:10:38 +0000626 self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
627 s = socket.socket()
Brian Curtin5ad0bd62010-11-05 15:47:45 +0000628 self.addCleanup(s.close)
Kristján Valur Jónsson847ec752009-09-27 21:10:38 +0000629 self.assertRaises(ValueError, s.ioctl, -1, None)
630 s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000631
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000632 def testGetaddrinfo(self):
633 try:
634 socket.getaddrinfo('localhost', 80)
635 except socket.gaierror as err:
636 if err.errno == socket.EAI_SERVICE:
637 # see http://bugs.python.org/issue1282647
638 self.skipTest("buggy libc version")
639 raise
640 # len of every sequence is supposed to be == 5
641 for info in socket.getaddrinfo(HOST, None):
642 self.assertEqual(len(info), 5)
643 # host can be a domain name, a string representation of an
644 # IPv4/v6 address or None
645 socket.getaddrinfo('localhost', 80)
646 socket.getaddrinfo('127.0.0.1', 80)
647 socket.getaddrinfo(None, 80)
648 if SUPPORTS_IPV6:
649 socket.getaddrinfo('::1', 80)
650 # port can be a string service name such as "http", a numeric
651 # port number or None
652 socket.getaddrinfo(HOST, "http")
653 socket.getaddrinfo(HOST, 80)
654 socket.getaddrinfo(HOST, None)
655 # test family and socktype filters
656 infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
657 for family, _, _, _, _ in infos:
658 self.assertEqual(family, socket.AF_INET)
659 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
660 for _, socktype, _, _, _ in infos:
661 self.assertEqual(socktype, socket.SOCK_STREAM)
662 # test proto and flags arguments
Giampaolo Rodolà677d95c2010-08-16 05:08:11 +0000663 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000664 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
665 # a server willing to support both IPv4 and IPv6 will
666 # usually do this
667 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
668 socket.AI_PASSIVE)
Giampaolo Rodolàccfb91c2010-08-17 15:30:23 +0000669 # test keyword arguments
670 a = socket.getaddrinfo(HOST, None)
671 b = socket.getaddrinfo(host=HOST, port=None)
672 self.assertEqual(a, b)
673 a = socket.getaddrinfo(HOST, None, socket.AF_INET)
674 b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
675 self.assertEqual(a, b)
676 a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
677 b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
678 self.assertEqual(a, b)
679 a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
680 b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
681 self.assertEqual(a, b)
682 a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
683 b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
684 self.assertEqual(a, b)
685 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
686 socket.AI_PASSIVE)
687 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
688 type=socket.SOCK_STREAM, proto=0,
689 flags=socket.AI_PASSIVE)
690 self.assertEqual(a, b)
Alexander Belopolskye239d232010-12-08 23:31:48 +0000691 # Issue #6697.
692 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
Giampaolo Rodolà419f7042010-08-14 16:45:41 +0000693
Martin v. Löwis112c0f32010-08-25 07:38:15 +0000694 def test_getnameinfo(self):
695 # only IP addresses are allowed
696 self.assertRaises(socket.error, socket.getnameinfo, ('mail.python.org',0), 0)
697
Daniel Stutzbach460ff3d2010-09-09 21:17:58 +0000698 @unittest.skipUnless(support.is_resource_enabled('network'),
699 'network is not enabled')
Martin v. Löwisfc0275a2010-08-22 19:33:47 +0000700 def test_idna(self):
Antoine Pitroud9107aa2010-09-04 18:50:35 +0000701 support.requires('network')
Martin v. Löwisfc0275a2010-08-22 19:33:47 +0000702 # these should all be successful
703 socket.gethostbyname('испытание.python.org')
704 socket.gethostbyname_ex('испытание.python.org')
Martin v. Löwis67e91ad2010-08-23 15:27:26 +0000705 socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM)
706 # this may not work if the forward lookup choses the IPv6 address, as that doesn't
707 # have a reverse entry yet
708 # socket.gethostbyaddr('испытание.python.org')
Christian Heimesfaf2f632008-01-06 16:59:19 +0000709
Antoine Pitrou6d7df632010-09-27 17:52:25 +0000710 def check_sendall_interrupted(self, with_timeout):
711 # socketpair() is not stricly required, but it makes things easier.
712 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
713 self.skipTest("signal.alarm and socket.socketpair required for this test")
714 # Our signal handlers clobber the C errno by calling a math function
715 # with an invalid domain value.
716 def ok_handler(*args):
717 self.assertRaises(ValueError, math.acosh, 0)
718 def raising_handler(*args):
719 self.assertRaises(ValueError, math.acosh, 0)
720 1 // 0
721 c, s = socket.socketpair()
722 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
723 try:
724 if with_timeout:
725 # Just above the one second minimum for signal.alarm
726 c.settimeout(1.5)
727 with self.assertRaises(ZeroDivisionError):
728 signal.alarm(1)
729 c.sendall(b"x" * (1024**2))
730 if with_timeout:
731 signal.signal(signal.SIGALRM, ok_handler)
732 signal.alarm(1)
733 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
734 finally:
735 signal.signal(signal.SIGALRM, old_alarm)
736 c.close()
737 s.close()
738
739 def test_sendall_interrupted(self):
740 self.check_sendall_interrupted(False)
741
742 def test_sendall_interrupted_with_timeout(self):
743 self.check_sendall_interrupted(True)
744
Antoine Pitroue033e062010-10-29 10:38:18 +0000745 def test_dealloc_warn(self):
746 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
747 r = repr(sock)
748 with self.assertWarns(ResourceWarning) as cm:
749 sock = None
750 support.gc_collect()
751 self.assertIn(r, str(cm.warning.args[0]))
752 # An open socket file object gets dereferenced after the socket
753 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
754 f = sock.makefile('rb')
755 r = repr(sock)
756 sock = None
757 support.gc_collect()
758 with self.assertWarns(ResourceWarning):
759 f = None
760 support.gc_collect()
761
Victor Stinnerc3a51ec2011-01-04 11:00:45 +0000762 def test_name_closed_socketio(self):
763 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
764 fp = sock.makefile("rb")
765 fp.close()
766 self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
767
Antoine Pitrou6d58d642011-03-20 23:56:36 +0100768 def test_pickle(self):
769 sock = socket.socket()
770 with sock:
771 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
772 self.assertRaises(TypeError, pickle.dumps, sock, protocol)
773
Antoine Pitrou6d7df632010-09-27 17:52:25 +0000774
Victor Stinner45df8202010-04-28 22:31:17 +0000775@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000776class BasicTCPTest(SocketConnectedTest):
777
778 def __init__(self, methodName='runTest'):
779 SocketConnectedTest.__init__(self, methodName=methodName)
780
781 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000782 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000783 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000784 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000785
786 def _testRecv(self):
787 self.serv_conn.send(MSG)
788
789 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000790 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000791 seg1 = self.cli_conn.recv(len(MSG) - 3)
792 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000793 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000794 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000795
796 def _testOverFlowRecv(self):
797 self.serv_conn.send(MSG)
798
799 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000800 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000801 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000802 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000803
804 def _testRecvFrom(self):
805 self.serv_conn.send(MSG)
806
807 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000808 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000809 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
810 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000811 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000812 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000813
814 def _testOverFlowRecvFrom(self):
815 self.serv_conn.send(MSG)
816
817 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000818 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000819 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000820 while 1:
821 read = self.cli_conn.recv(1024)
822 if not read:
823 break
Guido van Rossume531e292002-08-08 20:28:34 +0000824 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000825 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000826
827 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000828 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000829 self.serv_conn.sendall(big_chunk)
830
831 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000832 # Testing fromfd()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000833 fd = self.cli_conn.fileno()
834 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000835 self.addCleanup(sock.close)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +0000836 self.assertIsInstance(sock, socket.socket)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000837 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000838 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000839
840 def _testFromFd(self):
841 self.serv_conn.send(MSG)
842
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000843 def testDup(self):
844 # Testing dup()
845 sock = self.cli_conn.dup()
Brian Curtin21ebbb72010-11-02 02:07:09 +0000846 self.addCleanup(sock.close)
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000847 msg = sock.recv(1024)
848 self.assertEqual(msg, MSG)
849
850 def _testDup(self):
851 self.serv_conn.send(MSG)
852
Guido van Rossum24e4af82002-06-12 19:18:08 +0000853 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000854 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000855 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000856 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000857 # wait for _testShutdown to finish: on OS X, when the server
858 # closes the connection the client also becomes disconnected,
859 # and the client's shutdown call will fail. (Issue #4397.)
860 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000861
862 def _testShutdown(self):
863 self.serv_conn.send(MSG)
864 self.serv_conn.shutdown(2)
865
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000866 def testDetach(self):
867 # Testing detach()
868 fileno = self.cli_conn.fileno()
869 f = self.cli_conn.detach()
870 self.assertEqual(f, fileno)
871 # cli_conn cannot be used anymore...
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000872 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
873 self.cli_conn.close()
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000874 # ...but we can create another socket using the (still open)
875 # file descriptor
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000876 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
Brian Curtin21ebbb72010-11-02 02:07:09 +0000877 self.addCleanup(sock.close)
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000878 msg = sock.recv(1024)
879 self.assertEqual(msg, MSG)
880
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000881 def _testDetach(self):
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000882 self.serv_conn.send(MSG)
883
Victor Stinner45df8202010-04-28 22:31:17 +0000884@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000885class BasicUDPTest(ThreadedUDPSocketTest):
886
887 def __init__(self, methodName='runTest'):
888 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
889
890 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000891 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000892 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000893 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000894
895 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000896 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000897
Guido van Rossum1c938012002-06-12 21:17:20 +0000898 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000899 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000900 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000901 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000902
Guido van Rossum1c938012002-06-12 21:17:20 +0000903 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000904 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000905
Guido van Rossumd8faa362007-04-27 19:54:29 +0000906 def testRecvFromNegative(self):
907 # Negative lengths passed to recvfrom should give ValueError.
908 self.assertRaises(ValueError, self.serv.recvfrom, -1)
909
910 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000911 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000912
Victor Stinner45df8202010-04-28 22:31:17 +0000913@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000914class TCPCloserTest(ThreadedTCPSocketTest):
915
916 def testClose(self):
917 conn, addr = self.serv.accept()
918 conn.close()
919
920 sd = self.cli
921 read, write, err = select.select([sd], [], [], 1.0)
922 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000923 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000924
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000925 # Calling close() many times should be safe.
926 conn.close()
927 conn.close()
928
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000929 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000930 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000931 time.sleep(1.0)
932
Victor Stinner45df8202010-04-28 22:31:17 +0000933@unittest.skipUnless(thread, 'Threading required for this test.')
Dave Cole331708b2004-08-09 04:51:41 +0000934class BasicSocketPairTest(SocketPairTest):
935
936 def __init__(self, methodName='runTest'):
937 SocketPairTest.__init__(self, methodName=methodName)
938
Antoine Pitrou2e55fec2010-09-14 21:24:25 +0000939 def _check_defaults(self, sock):
940 self.assertIsInstance(sock, socket.socket)
941 if hasattr(socket, 'AF_UNIX'):
942 self.assertEqual(sock.family, socket.AF_UNIX)
943 else:
944 self.assertEqual(sock.family, socket.AF_INET)
945 self.assertEqual(sock.type, socket.SOCK_STREAM)
946 self.assertEqual(sock.proto, 0)
947
Antoine Pitrou9e0b8642010-09-14 18:00:02 +0000948 def _testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +0000949 self._check_defaults(self.cli)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +0000950
951 def testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +0000952 self._check_defaults(self.serv)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +0000953
Dave Cole331708b2004-08-09 04:51:41 +0000954 def testRecv(self):
955 msg = self.serv.recv(1024)
956 self.assertEqual(msg, MSG)
957
958 def _testRecv(self):
959 self.cli.send(MSG)
960
961 def testSend(self):
962 self.serv.send(MSG)
963
964 def _testSend(self):
965 msg = self.cli.recv(1024)
966 self.assertEqual(msg, MSG)
967
Victor Stinner45df8202010-04-28 22:31:17 +0000968@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000969class NonBlockingTCPTests(ThreadedTCPSocketTest):
970
971 def __init__(self, methodName='runTest'):
972 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
973
974 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000975 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000976 self.serv.setblocking(0)
977 start = time.time()
978 try:
979 self.serv.accept()
980 except socket.error:
981 pass
982 end = time.time()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000983 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000984
985 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000986 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000987
Antoine Pitroub1c54962010-10-14 15:05:38 +0000988 if hasattr(socket, "SOCK_NONBLOCK"):
989 def testInitNonBlocking(self):
Antoine Pitrou1cae8b52010-10-23 17:05:13 +0000990 v = linux_version()
991 if v < (2, 6, 28):
992 self.skipTest("Linux kernel 2.6.28 or higher required, not %s"
993 % ".".join(map(str, v)))
Antoine Pitroub1c54962010-10-14 15:05:38 +0000994 # reinit server socket
995 self.serv.close()
996 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
Antoine Pitrou1cae8b52010-10-23 17:05:13 +0000997 socket.SOCK_NONBLOCK)
Antoine Pitroub1c54962010-10-14 15:05:38 +0000998 self.port = support.bind_port(self.serv)
999 self.serv.listen(1)
1000 # actual testing
1001 start = time.time()
1002 try:
1003 self.serv.accept()
1004 except socket.error:
1005 pass
1006 end = time.time()
1007 self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.")
1008
1009 def _testInitNonBlocking(self):
1010 pass
1011
Antoine Pitrou600232b2011-01-05 21:03:42 +00001012 def testInheritFlags(self):
1013 # Issue #7995: when calling accept() on a listening socket with a
1014 # timeout, the resulting socket should not be non-blocking.
1015 self.serv.settimeout(10)
1016 try:
1017 conn, addr = self.serv.accept()
1018 message = conn.recv(len(MSG))
1019 finally:
1020 conn.close()
1021 self.serv.settimeout(None)
1022
1023 def _testInheritFlags(self):
1024 time.sleep(0.1)
1025 self.cli.connect((HOST, self.port))
1026 time.sleep(0.5)
1027 self.cli.send(MSG)
1028
Guido van Rossum24e4af82002-06-12 19:18:08 +00001029 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001030 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +00001031 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +00001032 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +00001033 conn, addr = self.serv.accept()
1034 except socket.error:
1035 pass
1036 else:
1037 self.fail("Error trying to do non-blocking accept.")
1038 read, write, err = select.select([self.serv], [], [])
1039 if self.serv in read:
1040 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001041 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001042 else:
1043 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +00001044
Guido van Rossum24e4af82002-06-12 19:18:08 +00001045 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001046 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +00001047 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001048
1049 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001050 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +00001051 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001052 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001053
1054 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +00001055 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +00001056 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001057
1058 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001059 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +00001060 conn, addr = self.serv.accept()
1061 conn.setblocking(0)
1062 try:
1063 msg = conn.recv(len(MSG))
1064 except socket.error:
1065 pass
1066 else:
1067 self.fail("Error trying to do non-blocking recv.")
1068 read, write, err = select.select([conn], [], [])
1069 if conn in read:
1070 msg = conn.recv(len(MSG))
Brian Curtin21ebbb72010-11-02 02:07:09 +00001071 conn.close()
Guido van Rossum76489682002-06-12 20:38:30 +00001072 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001073 else:
1074 self.fail("Error during select call to non-blocking socket.")
1075
1076 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001077 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001078 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001079 self.cli.send(MSG)
1080
Victor Stinner45df8202010-04-28 22:31:17 +00001081@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00001082class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001083 """Unit tests for the object returned by socket.makefile()
1084
Antoine Pitrou834bd812010-10-13 16:17:14 +00001085 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001086 the client connection. You can read from this file to
1087 get output from the server.
1088
Antoine Pitrou834bd812010-10-13 16:17:14 +00001089 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001090 server connection. You can write to this file to send output
1091 to the client.
1092 """
Guido van Rossum24e4af82002-06-12 19:18:08 +00001093
Guido van Rossume9f66142002-08-07 15:46:19 +00001094 bufsize = -1 # Use default buffer size
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001095 encoding = 'utf-8'
Antoine Pitrou834bd812010-10-13 16:17:14 +00001096 errors = 'strict'
1097 newline = None
1098
1099 read_mode = 'rb'
1100 read_msg = MSG
1101 write_mode = 'wb'
1102 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +00001103
Guido van Rossum24e4af82002-06-12 19:18:08 +00001104 def __init__(self, methodName='runTest'):
1105 SocketConnectedTest.__init__(self, methodName=methodName)
1106
1107 def setUp(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00001108 self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
1109 threading.Event() for i in range(4)]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001110 SocketConnectedTest.setUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001111 self.read_file = self.cli_conn.makefile(
1112 self.read_mode, self.bufsize,
1113 encoding = self.encoding,
1114 errors = self.errors,
1115 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001116
1117 def tearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00001118 self.serv_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00001119 self.read_file.close()
1120 self.assertTrue(self.read_file.closed)
1121 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00001122 SocketConnectedTest.tearDown(self)
1123
1124 def clientSetUp(self):
1125 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001126 self.write_file = self.serv_conn.makefile(
1127 self.write_mode, self.bufsize,
1128 encoding = self.encoding,
1129 errors = self.errors,
1130 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001131
1132 def clientTearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00001133 self.cli_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00001134 self.write_file.close()
1135 self.assertTrue(self.write_file.closed)
1136 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00001137 SocketConnectedTest.clientTearDown(self)
1138
Antoine Pitrou68e5c042011-02-25 23:07:44 +00001139 def testReadAfterTimeout(self):
1140 # Issue #7322: A file object must disallow further reads
1141 # after a timeout has occurred.
1142 self.cli_conn.settimeout(1)
1143 self.read_file.read(3)
1144 # First read raises a timeout
1145 self.assertRaises(socket.timeout, self.read_file.read, 1)
1146 # Second read is disallowed
1147 with self.assertRaises(IOError) as ctx:
1148 self.read_file.read(1)
1149 self.assertIn("cannot read from timed out object", str(ctx.exception))
1150
1151 def _testReadAfterTimeout(self):
1152 self.write_file.write(self.write_msg[0:3])
1153 self.write_file.flush()
1154 self.serv_finished.wait()
1155
Guido van Rossum24e4af82002-06-12 19:18:08 +00001156 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001157 # Performing small file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00001158 first_seg = self.read_file.read(len(self.read_msg)-3)
1159 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +00001160 msg = first_seg + second_seg
Antoine Pitrou834bd812010-10-13 16:17:14 +00001161 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001162
1163 def _testSmallRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001164 self.write_file.write(self.write_msg)
1165 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001166
Guido van Rossum8c943832002-08-08 01:00:28 +00001167 def testFullRead(self):
1168 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00001169 msg = self.read_file.read()
1170 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +00001171
1172 def _testFullRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001173 self.write_file.write(self.write_msg)
1174 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +00001175
Guido van Rossum24e4af82002-06-12 19:18:08 +00001176 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001177 # Performing unbuffered file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00001178 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001179 while 1:
Antoine Pitrou834bd812010-10-13 16:17:14 +00001180 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +00001181 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +00001182 break
Guido van Rossum8c943832002-08-08 01:00:28 +00001183 buf += char
Antoine Pitrou834bd812010-10-13 16:17:14 +00001184 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001185
1186 def _testUnbufferedRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001187 self.write_file.write(self.write_msg)
1188 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001189
1190 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001191 # Performing file readline test
Antoine Pitrou834bd812010-10-13 16:17:14 +00001192 line = self.read_file.readline()
1193 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001194
1195 def _testReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001196 self.write_file.write(self.write_msg)
1197 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001198
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001199 def testCloseAfterMakefile(self):
1200 # The file returned by makefile should keep the socket open.
1201 self.cli_conn.close()
1202 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00001203 msg = self.read_file.read()
1204 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001205
1206 def _testCloseAfterMakefile(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001207 self.write_file.write(self.write_msg)
1208 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001209
1210 def testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001211 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001212 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou834bd812010-10-13 16:17:14 +00001213 if isinstance(self.read_msg, str):
1214 msg = msg.decode()
1215 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001216
1217 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001218 self.write_file.write(self.write_msg)
1219 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00001220
Tim Peters116d83c2004-03-28 02:20:45 +00001221 def testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001222 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001223
1224 def _testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001225 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00001226
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001227 def testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001228 self.assertEqual(self.read_file.mode, self.read_mode)
1229 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001230
1231 def _testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001232 self.assertEqual(self.write_file.mode, self.write_mode)
1233 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00001234
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001235 def testRealClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001236 self.read_file.close()
1237 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001238 self.cli_conn.close()
1239 self.assertRaises(socket.error, self.cli_conn.getsockname)
1240
1241 def _testRealClose(self):
1242 pass
1243
1244
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001245class FileObjectInterruptedTestCase(unittest.TestCase):
1246 """Test that the file object correctly handles EINTR internally."""
1247
1248 class MockSocket(object):
1249 def __init__(self, recv_funcs=()):
1250 # A generator that returns callables that we'll call for each
1251 # call to recv().
1252 self._recv_step = iter(recv_funcs)
1253
1254 def recv_into(self, buffer):
1255 data = next(self._recv_step)()
1256 assert len(buffer) >= len(data)
1257 buffer[:len(data)] = data
1258 return len(data)
1259
1260 def _decref_socketios(self):
1261 pass
1262
1263 def _textiowrap_for_test(self, buffering=-1):
1264 raw = socket.SocketIO(self, "r")
1265 if buffering < 0:
1266 buffering = io.DEFAULT_BUFFER_SIZE
1267 if buffering == 0:
1268 return raw
1269 buffer = io.BufferedReader(raw, buffering)
1270 text = io.TextIOWrapper(buffer, None, None)
1271 text.mode = "rb"
1272 return text
1273
1274 @staticmethod
1275 def _raise_eintr():
1276 raise socket.error(errno.EINTR)
1277
1278 def _textiowrap_mock_socket(self, mock, buffering=-1):
1279 raw = socket.SocketIO(mock, "r")
1280 if buffering < 0:
1281 buffering = io.DEFAULT_BUFFER_SIZE
1282 if buffering == 0:
1283 return raw
1284 buffer = io.BufferedReader(raw, buffering)
1285 text = io.TextIOWrapper(buffer, None, None)
1286 text.mode = "rb"
1287 return text
1288
1289 def _test_readline(self, size=-1, buffering=-1):
1290 mock_sock = self.MockSocket(recv_funcs=[
1291 lambda : b"This is the first line\nAnd the sec",
1292 self._raise_eintr,
1293 lambda : b"ond line is here\n",
1294 lambda : b"",
1295 lambda : b"", # XXX(gps): io library does an extra EOF read
1296 ])
1297 fo = mock_sock._textiowrap_for_test(buffering=buffering)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001298 self.assertEqual(fo.readline(size), "This is the first line\n")
1299 self.assertEqual(fo.readline(size), "And the second line is here\n")
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001300
1301 def _test_read(self, size=-1, buffering=-1):
1302 mock_sock = self.MockSocket(recv_funcs=[
1303 lambda : b"This is the first line\nAnd the sec",
1304 self._raise_eintr,
1305 lambda : b"ond line is here\n",
1306 lambda : b"",
1307 lambda : b"", # XXX(gps): io library does an extra EOF read
1308 ])
1309 expecting = (b"This is the first line\n"
1310 b"And the second line is here\n")
1311 fo = mock_sock._textiowrap_for_test(buffering=buffering)
1312 if buffering == 0:
1313 data = b''
1314 else:
1315 data = ''
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001316 expecting = expecting.decode('utf-8')
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001317 while len(data) != len(expecting):
1318 part = fo.read(size)
1319 if not part:
1320 break
1321 data += part
Ezio Melottib3aedd42010-11-20 19:04:17 +00001322 self.assertEqual(data, expecting)
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001323
1324 def test_default(self):
1325 self._test_readline()
1326 self._test_readline(size=100)
1327 self._test_read()
1328 self._test_read(size=100)
1329
1330 def test_with_1k_buffer(self):
1331 self._test_readline(buffering=1024)
1332 self._test_readline(size=100, buffering=1024)
1333 self._test_read(buffering=1024)
1334 self._test_read(size=100, buffering=1024)
1335
1336 def _test_readline_no_buffer(self, size=-1):
1337 mock_sock = self.MockSocket(recv_funcs=[
1338 lambda : b"a",
1339 lambda : b"\n",
1340 lambda : b"B",
1341 self._raise_eintr,
1342 lambda : b"b",
1343 lambda : b"",
1344 ])
1345 fo = mock_sock._textiowrap_for_test(buffering=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001346 self.assertEqual(fo.readline(size), b"a\n")
1347 self.assertEqual(fo.readline(size), b"Bb")
Gregory P. Smithaafdca82010-01-04 04:50:36 +00001348
1349 def test_no_buffer(self):
1350 self._test_readline_no_buffer()
1351 self._test_readline_no_buffer(size=4)
1352 self._test_read(buffering=0)
1353 self._test_read(size=100, buffering=0)
1354
1355
Guido van Rossume9f66142002-08-07 15:46:19 +00001356class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1357
1358 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00001359
Guido van Rossume9f66142002-08-07 15:46:19 +00001360 In this case (and in this case only), it should be possible to
1361 create a file object, read a line from it, create another file
1362 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00001363 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00001364 when reading multiple requests from the same socket."""
1365
1366 bufsize = 0 # Use unbuffered mode
1367
1368 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001369 # Read a line, create a new file object, read another line with it
Antoine Pitrou834bd812010-10-13 16:17:14 +00001370 line = self.read_file.readline() # first line
1371 self.assertEqual(line, b"A. " + self.write_msg) # first line
1372 self.read_file = self.cli_conn.makefile('rb', 0)
1373 line = self.read_file.readline() # second line
1374 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00001375
1376 def _testUnbufferedReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001377 self.write_file.write(b"A. " + self.write_msg)
1378 self.write_file.write(b"B. " + self.write_msg)
1379 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00001380
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001381 def testMakefileClose(self):
1382 # The file returned by makefile should keep the socket open...
1383 self.cli_conn.close()
1384 msg = self.cli_conn.recv(1024)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001385 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001386 # ...until the file is itself closed
Antoine Pitrou834bd812010-10-13 16:17:14 +00001387 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001388 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1389
1390 def _testMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001391 self.write_file.write(self.write_msg)
1392 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001393
1394 def testMakefileCloseSocketDestroy(self):
1395 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001396 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001397 refcount_after = sys.getrefcount(self.cli_conn)
1398 self.assertEqual(refcount_before - 1, refcount_after)
1399
1400 def _testMakefileCloseSocketDestroy(self):
1401 pass
1402
Antoine Pitrou98b46702010-09-18 22:59:00 +00001403 # Non-blocking ops
Antoine Pitrou834bd812010-10-13 16:17:14 +00001404 # NOTE: to set `read_file` as non-blocking, we must call
Antoine Pitrou98b46702010-09-18 22:59:00 +00001405 # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
1406
1407 def testSmallReadNonBlocking(self):
1408 self.cli_conn.setblocking(False)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001409 self.assertEqual(self.read_file.readinto(bytearray(10)), None)
1410 self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001411 self.evt1.set()
1412 self.evt2.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001413 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou43bf0452011-04-04 01:21:37 +02001414 if first_seg is None:
1415 # Data not arrived (can happen under Windows), wait a bit
1416 time.sleep(0.5)
1417 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001418 buf = bytearray(10)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001419 n = self.read_file.readinto(buf)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001420 self.assertEqual(n, 3)
1421 msg = first_seg + buf[:n]
Antoine Pitrou834bd812010-10-13 16:17:14 +00001422 self.assertEqual(msg, self.read_msg)
1423 self.assertEqual(self.read_file.readinto(bytearray(16)), None)
1424 self.assertEqual(self.read_file.read(1), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001425
1426 def _testSmallReadNonBlocking(self):
1427 self.evt1.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00001428 self.write_file.write(self.write_msg)
1429 self.write_file.flush()
Antoine Pitrou98b46702010-09-18 22:59:00 +00001430 self.evt2.set()
1431 # Avoid cloding the socket before the server test has finished,
1432 # otherwise system recv() will return 0 instead of EWOULDBLOCK.
1433 self.serv_finished.wait(5.0)
1434
1435 def testWriteNonBlocking(self):
1436 self.cli_finished.wait(5.0)
1437 # The client thread can't skip directly - the SkipTest exception
1438 # would appear as a failure.
1439 if self.serv_skipped:
1440 self.skipTest(self.serv_skipped)
1441
1442 def _testWriteNonBlocking(self):
1443 self.serv_skipped = None
1444 self.serv_conn.setblocking(False)
1445 # Try to saturate the socket buffer pipe with repeated large writes.
1446 BIG = b"x" * (1024 ** 2)
1447 LIMIT = 10
1448 # The first write() succeeds since a chunk of data can be buffered
Antoine Pitrou834bd812010-10-13 16:17:14 +00001449 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001450 self.assertGreater(n, 0)
1451 for i in range(LIMIT):
Antoine Pitrou834bd812010-10-13 16:17:14 +00001452 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00001453 if n is None:
1454 # Succeeded
1455 break
1456 self.assertGreater(n, 0)
1457 else:
1458 # Let us know that this test didn't manage to establish
1459 # the expected conditions. This is not a failure in itself but,
1460 # if it happens repeatedly, the test should be fixed.
1461 self.serv_skipped = "failed to saturate the socket buffer"
1462
Gregory P. Smithde3369f2009-01-12 04:50:11 +00001463
Guido van Rossum8c943832002-08-08 01:00:28 +00001464class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1465
1466 bufsize = 1 # Default-buffered for reading; line-buffered for writing
1467
1468
1469class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1470
1471 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00001472
Thomas Woutersb2137042007-02-01 18:02:27 +00001473
Antoine Pitrou834bd812010-10-13 16:17:14 +00001474class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
1475 """Tests for socket.makefile() in text mode (rather than binary)"""
1476
1477 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001478 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00001479 write_mode = 'wb'
1480 write_msg = MSG
1481 newline = ''
1482
1483
1484class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
1485 """Tests for socket.makefile() in text mode (rather than binary)"""
1486
1487 read_mode = 'rb'
1488 read_msg = MSG
1489 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001490 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00001491 newline = ''
1492
1493
1494class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
1495 """Tests for socket.makefile() in text mode (rather than binary)"""
1496
1497 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001498 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00001499 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001500 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00001501 newline = ''
1502
1503
Guido van Rossumd8faa362007-04-27 19:54:29 +00001504class NetworkConnectionTest(object):
1505 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001506
Guido van Rossumd8faa362007-04-27 19:54:29 +00001507 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001508 # We're inherited below by BasicTCPTest2, which also inherits
1509 # BasicTCPTest, which defines self.port referenced below.
1510 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001511 self.serv_conn = self.cli
1512
1513class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1514 """Tests that NetworkConnection does not break existing TCP functionality.
1515 """
1516
1517class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001518
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00001519 class MockSocket(socket.socket):
1520 def connect(self, *args):
1521 raise socket.timeout('timed out')
1522
1523 @contextlib.contextmanager
1524 def mocked_socket_module(self):
1525 """Return a socket which times out on connect"""
1526 old_socket = socket.socket
1527 socket.socket = self.MockSocket
1528 try:
1529 yield
1530 finally:
1531 socket.socket = old_socket
1532
1533 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001534 port = support.find_unused_port()
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00001535 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001536 self.addCleanup(cli.close)
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00001537 with self.assertRaises(socket.error) as cm:
1538 cli.connect((HOST, port))
1539 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
1540
1541 def test_create_connection(self):
1542 # Issue #9792: errors raised by create_connection() should have
1543 # a proper errno attribute.
1544 port = support.find_unused_port()
1545 with self.assertRaises(socket.error) as cm:
1546 socket.create_connection((HOST, port))
1547 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
1548
1549 def test_create_connection_timeout(self):
1550 # Issue #9792: create_connection() should not recast timeout errors
1551 # as generic socket errors.
1552 with self.mocked_socket_module():
1553 with self.assertRaises(socket.timeout):
1554 socket.create_connection((HOST, 1234))
1555
Guido van Rossumd8faa362007-04-27 19:54:29 +00001556
Victor Stinner45df8202010-04-28 22:31:17 +00001557@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001558class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1559
1560 def __init__(self, methodName='runTest'):
1561 SocketTCPTest.__init__(self, methodName=methodName)
1562 ThreadableTest.__init__(self)
1563
1564 def clientSetUp(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00001565 self.source_port = support.find_unused_port()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001566
1567 def clientTearDown(self):
1568 self.cli.close()
1569 self.cli = None
1570 ThreadableTest.clientTearDown(self)
1571
1572 def _justAccept(self):
1573 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001574 conn.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575
1576 testFamily = _justAccept
1577 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001578 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001579 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 self.assertEqual(self.cli.family, 2)
1581
Gregory P. Smitha81d8812010-01-03 15:09:32 +00001582 testSourceAddress = _justAccept
1583 def _testSourceAddress(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00001584 self.cli = socket.create_connection((HOST, self.port), timeout=30,
1585 source_address=('', self.source_port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00001586 self.addCleanup(self.cli.close)
Gregory P. Smithb4066372010-01-03 03:28:29 +00001587 self.assertEqual(self.cli.getsockname()[1], self.source_port)
Gregory P. Smitha81d8812010-01-03 15:09:32 +00001588 # The port number being used is sufficient to show that the bind()
1589 # call happened.
Gregory P. Smithb4066372010-01-03 03:28:29 +00001590
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591 testTimeoutDefault = _justAccept
1592 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001593 # passing no explicit timeout uses socket's global default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001594 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001595 socket.setdefaulttimeout(42)
1596 try:
1597 self.cli = socket.create_connection((HOST, self.port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00001598 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001599 finally:
1600 socket.setdefaulttimeout(None)
Ezio Melottib3aedd42010-11-20 19:04:17 +00001601 self.assertEqual(self.cli.gettimeout(), 42)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001602
1603 testTimeoutNone = _justAccept
1604 def _testTimeoutNone(self):
1605 # None timeout means the same as sock.settimeout(None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001606 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001607 socket.setdefaulttimeout(30)
1608 try:
1609 self.cli = socket.create_connection((HOST, self.port), timeout=None)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001610 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001611 finally:
1612 socket.setdefaulttimeout(None)
1613 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614
1615 testTimeoutValueNamed = _justAccept
1616 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001617 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001618 self.assertEqual(self.cli.gettimeout(), 30)
1619
1620 testTimeoutValueNonamed = _justAccept
1621 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001622 self.cli = socket.create_connection((HOST, self.port), 30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001623 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001624 self.assertEqual(self.cli.gettimeout(), 30)
1625
Victor Stinner45df8202010-04-28 22:31:17 +00001626@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1628
1629 def __init__(self, methodName='runTest'):
1630 SocketTCPTest.__init__(self, methodName=methodName)
1631 ThreadableTest.__init__(self)
1632
1633 def clientSetUp(self):
1634 pass
1635
1636 def clientTearDown(self):
1637 self.cli.close()
1638 self.cli = None
1639 ThreadableTest.clientTearDown(self)
1640
1641 def testInsideTimeout(self):
1642 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001643 self.addCleanup(conn.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001645 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001646 testOutsideTimeout = testInsideTimeout
1647
1648 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001649 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001651 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
1653 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001654 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001655 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001656
1657
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001658class TCPTimeoutTest(SocketTCPTest):
1659
1660 def testTCPTimeout(self):
1661 def raise_timeout(*args, **kwargs):
1662 self.serv.settimeout(1.0)
1663 self.serv.accept()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001664 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001665 "Error generating a timeout exception (TCP)")
1666
1667 def testTimeoutZero(self):
1668 ok = False
1669 try:
1670 self.serv.settimeout(0.0)
1671 foo = self.serv.accept()
1672 except socket.timeout:
1673 self.fail("caught timeout instead of error (TCP)")
1674 except socket.error:
1675 ok = True
1676 except:
1677 self.fail("caught unexpected exception (TCP)")
1678 if not ok:
1679 self.fail("accept() returned success when we did not expect it")
1680
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001681 def testInterruptedTimeout(self):
1682 # XXX I don't know how to do this test on MSWindows or any other
1683 # plaform that doesn't support signal.alarm() or os.kill(), though
1684 # the bug should have existed on all platforms.
1685 if not hasattr(signal, "alarm"):
1686 return # can only test on *nix
1687 self.serv.settimeout(5.0) # must be longer than alarm
1688 class Alarm(Exception):
1689 pass
1690 def alarm_handler(signal, frame):
1691 raise Alarm
1692 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1693 try:
1694 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1695 try:
1696 foo = self.serv.accept()
1697 except socket.timeout:
1698 self.fail("caught timeout instead of Alarm")
1699 except Alarm:
1700 pass
1701 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001702 self.fail("caught other exception instead of Alarm:"
1703 " %s(%s):\n%s" %
1704 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001705 else:
1706 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001707 finally:
1708 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001709 except Alarm:
1710 self.fail("got Alarm in wrong place")
1711 finally:
1712 # no alarm can be pending. Safe to restore old handler.
1713 signal.signal(signal.SIGALRM, old_alarm)
1714
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001715class UDPTimeoutTest(SocketTCPTest):
1716
1717 def testUDPTimeout(self):
1718 def raise_timeout(*args, **kwargs):
1719 self.serv.settimeout(1.0)
1720 self.serv.recv(1024)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001721 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001722 "Error generating a timeout exception (UDP)")
1723
1724 def testTimeoutZero(self):
1725 ok = False
1726 try:
1727 self.serv.settimeout(0.0)
1728 foo = self.serv.recv(1024)
1729 except socket.timeout:
1730 self.fail("caught timeout instead of error (UDP)")
1731 except socket.error:
1732 ok = True
1733 except:
1734 self.fail("caught unexpected exception (UDP)")
1735 if not ok:
1736 self.fail("recv() returned success when we did not expect it")
1737
1738class TestExceptions(unittest.TestCase):
1739
1740 def testExceptionTree(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001741 self.assertTrue(issubclass(socket.error, Exception))
1742 self.assertTrue(issubclass(socket.herror, socket.error))
1743 self.assertTrue(issubclass(socket.gaierror, socket.error))
1744 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001745
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001746class TestLinuxAbstractNamespace(unittest.TestCase):
1747
1748 UNIX_PATH_MAX = 108
1749
1750 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001751 address = b"\x00python-test-hello\x00\xff"
Victor Stinner1d5eb342011-01-03 14:30:46 +00001752 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
1753 s1.bind(address)
1754 s1.listen(1)
1755 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
1756 s2.connect(s1.getsockname())
1757 with s1.accept()[0] as s3:
1758 self.assertEqual(s1.getsockname(), address)
1759 self.assertEqual(s2.getpeername(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001760
1761 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001762 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Victor Stinner1d5eb342011-01-03 14:30:46 +00001763 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
1764 s.bind(address)
1765 self.assertEqual(s.getsockname(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001766
1767 def testNameOverflow(self):
1768 address = "\x00" + "h" * self.UNIX_PATH_MAX
Victor Stinner1d5eb342011-01-03 14:30:46 +00001769 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
1770 self.assertRaises(socket.error, s.bind, address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001771
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001772
Victor Stinner45df8202010-04-28 22:31:17 +00001773@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001774class BufferIOTest(SocketConnectedTest):
1775 """
1776 Test the buffer versions of socket.recv() and socket.send().
1777 """
1778 def __init__(self, methodName='runTest'):
1779 SocketConnectedTest.__init__(self, methodName=methodName)
1780
Antoine Pitrou25480782010-03-17 22:50:28 +00001781 def testRecvIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001782 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001783 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001785 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786 self.assertEqual(msg, MSG)
1787
Antoine Pitrou25480782010-03-17 22:50:28 +00001788 def _testRecvIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001789 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790 self.serv_conn.send(buf)
1791
Antoine Pitrou25480782010-03-17 22:50:28 +00001792 def testRecvIntoBytearray(self):
1793 buf = bytearray(1024)
1794 nbytes = self.cli_conn.recv_into(buf)
1795 self.assertEqual(nbytes, len(MSG))
1796 msg = buf[:len(MSG)]
1797 self.assertEqual(msg, MSG)
1798
1799 _testRecvIntoBytearray = _testRecvIntoArray
1800
1801 def testRecvIntoMemoryview(self):
1802 buf = bytearray(1024)
1803 nbytes = self.cli_conn.recv_into(memoryview(buf))
1804 self.assertEqual(nbytes, len(MSG))
1805 msg = buf[:len(MSG)]
1806 self.assertEqual(msg, MSG)
1807
1808 _testRecvIntoMemoryview = _testRecvIntoArray
1809
1810 def testRecvFromIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001811 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001812 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001813 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001814 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001815 self.assertEqual(msg, MSG)
1816
Antoine Pitrou25480782010-03-17 22:50:28 +00001817 def _testRecvFromIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001818 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001819 self.serv_conn.send(buf)
1820
Antoine Pitrou25480782010-03-17 22:50:28 +00001821 def testRecvFromIntoBytearray(self):
1822 buf = bytearray(1024)
1823 nbytes, addr = self.cli_conn.recvfrom_into(buf)
1824 self.assertEqual(nbytes, len(MSG))
1825 msg = buf[:len(MSG)]
1826 self.assertEqual(msg, MSG)
1827
1828 _testRecvFromIntoBytearray = _testRecvFromIntoArray
1829
1830 def testRecvFromIntoMemoryview(self):
1831 buf = bytearray(1024)
1832 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
1833 self.assertEqual(nbytes, len(MSG))
1834 msg = buf[:len(MSG)]
1835 self.assertEqual(msg, MSG)
1836
1837 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
1838
Christian Heimes043d6f62008-01-07 17:19:16 +00001839
1840TIPC_STYPE = 2000
1841TIPC_LOWER = 200
1842TIPC_UPPER = 210
1843
1844def isTipcAvailable():
1845 """Check if the TIPC module is loaded
1846
1847 The TIPC module is not loaded automatically on Ubuntu and probably
1848 other Linux distros.
1849 """
1850 if not hasattr(socket, "AF_TIPC"):
1851 return False
1852 if not os.path.isfile("/proc/modules"):
1853 return False
1854 with open("/proc/modules") as f:
1855 for line in f:
1856 if line.startswith("tipc "):
1857 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001858 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001859 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1860 return False
1861
1862class TIPCTest (unittest.TestCase):
1863 def testRDM(self):
1864 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1865 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1866
1867 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1868 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1869 TIPC_LOWER, TIPC_UPPER)
1870 srv.bind(srvaddr)
1871
1872 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1873 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1874 cli.sendto(MSG, sendaddr)
1875
1876 msg, recvaddr = srv.recvfrom(1024)
1877
1878 self.assertEqual(cli.getsockname(), recvaddr)
1879 self.assertEqual(msg, MSG)
1880
1881
1882class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1883 def __init__(self, methodName = 'runTest'):
1884 unittest.TestCase.__init__(self, methodName = methodName)
1885 ThreadableTest.__init__(self)
1886
1887 def setUp(self):
1888 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1889 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1890 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1891 TIPC_LOWER, TIPC_UPPER)
1892 self.srv.bind(srvaddr)
1893 self.srv.listen(5)
1894 self.serverExplicitReady()
1895 self.conn, self.connaddr = self.srv.accept()
1896
1897 def clientSetUp(self):
1898 # The is a hittable race between serverExplicitReady() and the
1899 # accept() call; sleep a little while to avoid it, otherwise
1900 # we could get an exception
1901 time.sleep(0.1)
1902 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1903 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1904 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1905 self.cli.connect(addr)
1906 self.cliaddr = self.cli.getsockname()
1907
1908 def testStream(self):
1909 msg = self.conn.recv(1024)
1910 self.assertEqual(msg, MSG)
1911 self.assertEqual(self.cliaddr, self.connaddr)
1912
1913 def _testStream(self):
1914 self.cli.send(MSG)
1915 self.cli.close()
1916
1917
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00001918@unittest.skipUnless(thread, 'Threading required for this test.')
1919class ContextManagersTest(ThreadedTCPSocketTest):
1920
1921 def _testSocketClass(self):
1922 # base test
1923 with socket.socket() as sock:
1924 self.assertFalse(sock._closed)
1925 self.assertTrue(sock._closed)
1926 # close inside with block
1927 with socket.socket() as sock:
1928 sock.close()
1929 self.assertTrue(sock._closed)
1930 # exception inside with block
1931 with socket.socket() as sock:
1932 self.assertRaises(socket.error, sock.sendall, b'foo')
1933 self.assertTrue(sock._closed)
1934
1935 def testCreateConnectionBase(self):
1936 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001937 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00001938 data = conn.recv(1024)
1939 conn.sendall(data)
1940
1941 def _testCreateConnectionBase(self):
1942 address = self.serv.getsockname()
1943 with socket.create_connection(address) as sock:
1944 self.assertFalse(sock._closed)
1945 sock.sendall(b'foo')
1946 self.assertEqual(sock.recv(1024), b'foo')
1947 self.assertTrue(sock._closed)
1948
1949 def testCreateConnectionClose(self):
1950 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001951 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00001952 data = conn.recv(1024)
1953 conn.sendall(data)
1954
1955 def _testCreateConnectionClose(self):
1956 address = self.serv.getsockname()
1957 with socket.create_connection(address) as sock:
1958 sock.close()
1959 self.assertTrue(sock._closed)
1960 self.assertRaises(socket.error, sock.sendall, b'foo')
1961
Antoine Pitrouacd0fda2010-10-23 17:01:44 +00001962
Antoine Pitroub1c54962010-10-14 15:05:38 +00001963@unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
1964 "SOCK_CLOEXEC not defined")
1965@unittest.skipUnless(fcntl, "module fcntl not available")
1966class CloexecConstantTest(unittest.TestCase):
1967 def test_SOCK_CLOEXEC(self):
Antoine Pitrouacd0fda2010-10-23 17:01:44 +00001968 v = linux_version()
1969 if v < (2, 6, 28):
1970 self.skipTest("Linux kernel 2.6.28 or higher required, not %s"
1971 % ".".join(map(str, v)))
Victor Stinner1d5eb342011-01-03 14:30:46 +00001972 with socket.socket(socket.AF_INET,
1973 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
1974 self.assertTrue(s.type & socket.SOCK_CLOEXEC)
1975 self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
Antoine Pitroub1c54962010-10-14 15:05:38 +00001976
1977
1978@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
1979 "SOCK_NONBLOCK not defined")
1980class NonblockConstantTest(unittest.TestCase):
1981 def checkNonblock(self, s, nonblock=True, timeout=0.0):
1982 if nonblock:
1983 self.assertTrue(s.type & socket.SOCK_NONBLOCK)
1984 self.assertEqual(s.gettimeout(), timeout)
1985 else:
1986 self.assertFalse(s.type & socket.SOCK_NONBLOCK)
1987 self.assertEqual(s.gettimeout(), None)
1988
1989 def test_SOCK_NONBLOCK(self):
Antoine Pitrouacd0fda2010-10-23 17:01:44 +00001990 v = linux_version()
1991 if v < (2, 6, 28):
1992 self.skipTest("Linux kernel 2.6.28 or higher required, not %s"
1993 % ".".join(map(str, v)))
Antoine Pitroub1c54962010-10-14 15:05:38 +00001994 # a lot of it seems silly and redundant, but I wanted to test that
1995 # changing back and forth worked ok
Victor Stinner1d5eb342011-01-03 14:30:46 +00001996 with socket.socket(socket.AF_INET,
1997 socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
1998 self.checkNonblock(s)
1999 s.setblocking(1)
2000 self.checkNonblock(s, False)
2001 s.setblocking(0)
2002 self.checkNonblock(s)
2003 s.settimeout(None)
2004 self.checkNonblock(s, False)
2005 s.settimeout(2.0)
2006 self.checkNonblock(s, timeout=2.0)
2007 s.setblocking(1)
2008 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00002009 # defaulttimeout
2010 t = socket.getdefaulttimeout()
2011 socket.setdefaulttimeout(0.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00002012 with socket.socket() as s:
2013 self.checkNonblock(s)
Antoine Pitroub1c54962010-10-14 15:05:38 +00002014 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00002015 with socket.socket() as s:
2016 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00002017 socket.setdefaulttimeout(2.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00002018 with socket.socket() as s:
2019 self.checkNonblock(s, timeout=2.0)
Antoine Pitroub1c54962010-10-14 15:05:38 +00002020 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00002021 with socket.socket() as s:
2022 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00002023 socket.setdefaulttimeout(t)
2024
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00002025
Guido van Rossumb995eb72002-07-31 16:08:40 +00002026def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002027 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Ronald Oussoren94f25282010-05-05 19:11:21 +00002028 TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00002029
2030 tests.extend([
2031 NonBlockingTCPTests,
2032 FileObjectClassTestCase,
Gregory P. Smithaafdca82010-01-04 04:50:36 +00002033 FileObjectInterruptedTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +00002034 UnbufferedFileObjectClassTestCase,
2035 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00002036 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou834bd812010-10-13 16:17:14 +00002037 UnicodeReadFileObjectClassTestCase,
2038 UnicodeWriteFileObjectClassTestCase,
2039 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00002040 NetworkConnectionNoServer,
2041 NetworkConnectionAttributesTest,
2042 NetworkConnectionBehaviourTest,
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00002043 ContextManagersTest,
Antoine Pitroub1c54962010-10-14 15:05:38 +00002044 CloexecConstantTest,
2045 NonblockConstantTest
Walter Dörwald21d3a322003-05-01 17:45:56 +00002046 ])
Dave Cole331708b2004-08-09 04:51:41 +00002047 if hasattr(socket, "socketpair"):
2048 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002049 if sys.platform == 'linux2':
2050 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00002051 if isTipcAvailable():
2052 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00002053 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002054
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002055 thread_info = support.threading_setup()
2056 support.run_unittest(*tests)
2057 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00002058
2059if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00002060 test_main()