blob: 731827c84b9710f777df90435e45261f4d95a613 [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread as thread
10import threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000011import time
12import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000013import queue
Jack Jansen522e7692002-09-06 21:57:50 +000014import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000015import os
16import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000017from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000018import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000019
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020HOST = support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000021MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000022
Guido van Rossum24e4af82002-06-12 19:18:08 +000023class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000024
Guido van Rossum24e4af82002-06-12 19:18:08 +000025 def setUp(self):
26 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000027 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000028 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000029
Guido van Rossum24e4af82002-06-12 19:18:08 +000030 def tearDown(self):
31 self.serv.close()
32 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000033
Guido van Rossum24e4af82002-06-12 19:18:08 +000034class SocketUDPTest(unittest.TestCase):
35
36 def setUp(self):
37 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000038 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000039
40 def tearDown(self):
41 self.serv.close()
42 self.serv = None
43
44class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000045 """Threadable Test class
46
47 The ThreadableTest class makes it easy to create a threaded
48 client/server pair from an existing unit test. To create a
49 new threaded class from an existing unit test, use multiple
50 inheritance:
51
52 class NewClass (OldClass, ThreadableTest):
53 pass
54
55 This class defines two new fixture functions with obvious
56 purposes for overriding:
57
58 clientSetUp ()
59 clientTearDown ()
60
61 Any new test functions within the class must then define
62 tests in pairs, where the test name is preceeded with a
63 '_' to indicate the client portion of the test. Ex:
64
65 def testFoo(self):
66 # Server portion
67
68 def _testFoo(self):
69 # Client portion
70
71 Any exceptions raised by the clients during their tests
72 are caught and transferred to the main thread to alert
73 the testing framework.
74
75 Note, the server setup function cannot call any blocking
76 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000077 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000078 the blocking call (such as in setting up a client/server
79 connection and performing the accept() in setUp().
80 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000081
82 def __init__(self):
83 # Swap the true setup function
84 self.__setUp = self.setUp
85 self.__tearDown = self.tearDown
86 self.setUp = self._setUp
87 self.tearDown = self._tearDown
88
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000089 def serverExplicitReady(self):
90 """This method allows the server to explicitly indicate that
91 it wants the client thread to proceed. This is useful if the
92 server is about to execute a blocking routine that is
93 dependent upon the client thread during its setup routine."""
94 self.server_ready.set()
95
Guido van Rossum24e4af82002-06-12 19:18:08 +000096 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000097 self.server_ready = threading.Event()
98 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000099 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000100 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000101
102 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000103 methodname = self.id()
104 i = methodname.rfind('.')
105 methodname = methodname[i+1:]
106 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000107 self.client_thread = thread.start_new_thread(
108 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000109
110 self.__setUp()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000111 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000112 self.server_ready.set()
113 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000114
115 def _tearDown(self):
116 self.__tearDown()
117 self.done.wait()
118
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000119 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000120 msg = self.queue.get()
121 self.fail(msg)
122
123 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000124 self.server_ready.wait()
125 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000126 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000127 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000128 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129 try:
130 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000131 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000132 self.queue.put(strerror)
133 self.clientTearDown()
134
135 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000136 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000137
138 def clientTearDown(self):
139 self.done.set()
140 thread.exit()
141
142class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
143
144 def __init__(self, methodName='runTest'):
145 SocketTCPTest.__init__(self, methodName=methodName)
146 ThreadableTest.__init__(self)
147
148 def clientSetUp(self):
149 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
150
151 def clientTearDown(self):
152 self.cli.close()
153 self.cli = None
154 ThreadableTest.clientTearDown(self)
155
156class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
157
158 def __init__(self, methodName='runTest'):
159 SocketUDPTest.__init__(self, methodName=methodName)
160 ThreadableTest.__init__(self)
161
162 def clientSetUp(self):
163 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
164
165class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000166 """Socket tests for client-server connection.
167
168 self.cli_conn is a client socket connected to the server. The
169 setUp() method guarantees that it is connected to the server.
170 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000171
172 def __init__(self, methodName='runTest'):
173 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
174
175 def setUp(self):
176 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000177 # Indicate explicitly we're ready for the client thread to
178 # proceed and then perform the blocking call to accept
179 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000180 conn, addr = self.serv.accept()
181 self.cli_conn = conn
182
183 def tearDown(self):
184 self.cli_conn.close()
185 self.cli_conn = None
186 ThreadedTCPSocketTest.tearDown(self)
187
188 def clientSetUp(self):
189 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000190 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000191 self.serv_conn = self.cli
192
193 def clientTearDown(self):
194 self.serv_conn.close()
195 self.serv_conn = None
196 ThreadedTCPSocketTest.clientTearDown(self)
197
Dave Cole331708b2004-08-09 04:51:41 +0000198class SocketPairTest(unittest.TestCase, ThreadableTest):
199
200 def __init__(self, methodName='runTest'):
201 unittest.TestCase.__init__(self, methodName=methodName)
202 ThreadableTest.__init__(self)
203
204 def setUp(self):
205 self.serv, self.cli = socket.socketpair()
206
207 def tearDown(self):
208 self.serv.close()
209 self.serv = None
210
211 def clientSetUp(self):
212 pass
213
214 def clientTearDown(self):
215 self.cli.close()
216 self.cli = None
217 ThreadableTest.clientTearDown(self)
218
Tim Peters494aaee2004-08-09 18:54:11 +0000219
Guido van Rossum24e4af82002-06-12 19:18:08 +0000220#######################################################################
221## Begin Tests
222
223class GeneralModuleTests(unittest.TestCase):
224
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000225 def test_repr(self):
226 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
227 self.assert_(repr(s).startswith("<socket.socket object"))
228
Raymond Hettinger027bb632004-05-31 03:09:25 +0000229 def test_weakref(self):
230 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
231 p = proxy(s)
232 self.assertEqual(p.fileno(), s.fileno())
233 s.close()
234 s = None
235 try:
236 p.fileno()
237 except ReferenceError:
238 pass
239 else:
240 self.fail('Socket proxy still exists')
241
Guido van Rossum24e4af82002-06-12 19:18:08 +0000242 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000243 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000244 def raise_error(*args, **kwargs):
245 raise socket.error
246 def raise_herror(*args, **kwargs):
247 raise socket.herror
248 def raise_gaierror(*args, **kwargs):
249 raise socket.gaierror
250 self.failUnlessRaises(socket.error, raise_error,
251 "Error raising socket exception.")
252 self.failUnlessRaises(socket.error, raise_herror,
253 "Error raising socket exception.")
254 self.failUnlessRaises(socket.error, raise_gaierror,
255 "Error raising socket exception.")
256
257 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000258 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259 socket.AF_INET
260 socket.SOCK_STREAM
261 socket.SOCK_DGRAM
262 socket.SOCK_RAW
263 socket.SOCK_RDM
264 socket.SOCK_SEQPACKET
265 socket.SOL_SOCKET
266 socket.SO_REUSEADDR
267
Guido van Rossum654c11e2002-06-13 20:24:17 +0000268 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000269 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000270 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000271 try:
272 ip = socket.gethostbyname(hostname)
273 except socket.error:
274 # Probably name lookup wasn't set up right; skip this test
275 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000276 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000277 try:
278 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
279 except socket.error:
280 # Probably a similar problem as above; skip this test
281 return
Brett Cannon01668a12005-03-11 00:04:17 +0000282 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000284 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000286
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000287 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000288 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000289 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000290 try:
291 # On some versions, this loses a reference
292 orig = sys.getrefcount(__name__)
293 socket.getnameinfo(__name__,0)
294 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000295 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000296 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000297
Guido van Rossum24e4af82002-06-12 19:18:08 +0000298 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000299 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000300 try:
301 # On some versions, this crashes the interpreter.
302 socket.getnameinfo(('x', 0, 0, 0), 0)
303 except socket.error:
304 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000305
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000306 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000307 # This just checks that htons etc. are their own inverse,
308 # when looking at the lower 16 or 32 bits.
309 sizes = {socket.htonl: 32, socket.ntohl: 32,
310 socket.htons: 16, socket.ntohs: 16}
311 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000312 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000313 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
314 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000315
Guido van Rossuma2627af2002-09-14 00:58:46 +0000316 swapped = func(mask)
317 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000318 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000319
Guido van Rossum018919a2007-01-15 00:07:32 +0000320 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000321 good_values = [ 1, 2, 3, 1, 2, 3 ]
322 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000323 for k in good_values:
324 socket.ntohl(k)
325 socket.ntohs(k)
326 socket.htonl(k)
327 socket.htons(k)
328 for k in bad_values:
329 self.assertRaises(OverflowError, socket.ntohl, k)
330 self.assertRaises(OverflowError, socket.ntohs, k)
331 self.assertRaises(OverflowError, socket.htonl, k)
332 self.assertRaises(OverflowError, socket.htons, k)
333
Barry Warsaw11b91a02004-06-28 00:50:43 +0000334 def testGetServBy(self):
335 eq = self.assertEqual
336 # Find one service that exists, then check all the related interfaces.
337 # I've ordered this by protocols that have both a tcp and udp
338 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000339 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000340 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000341 # avoid the 'echo' service on this platform, as there is an
342 # assumption breaking non-standard port/protocol entry
343 services = ('daytime', 'qotd', 'domain')
344 else:
345 services = ('echo', 'daytime', 'domain')
346 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000347 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000348 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000349 break
350 except socket.error:
351 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000352 else:
353 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000354 # Try same call with optional protocol omitted
355 port2 = socket.getservbyname(service)
356 eq(port, port2)
357 # Try udp, but don't barf it it doesn't exist
358 try:
359 udpport = socket.getservbyname(service, 'udp')
360 except socket.error:
361 udpport = None
362 else:
363 eq(udpport, port)
364 # Now make sure the lookup by port returns the same service name
365 eq(socket.getservbyport(port2), service)
366 eq(socket.getservbyport(port, 'tcp'), service)
367 if udpport is not None:
368 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000369
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000370 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000371 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000372 # The default timeout should initially be None
373 self.assertEqual(socket.getdefaulttimeout(), None)
374 s = socket.socket()
375 self.assertEqual(s.gettimeout(), None)
376 s.close()
377
378 # Set the default timeout to 10, and see if it propagates
379 socket.setdefaulttimeout(10)
380 self.assertEqual(socket.getdefaulttimeout(), 10)
381 s = socket.socket()
382 self.assertEqual(s.gettimeout(), 10)
383 s.close()
384
385 # Reset the default timeout to None, and see if it propagates
386 socket.setdefaulttimeout(None)
387 self.assertEqual(socket.getdefaulttimeout(), None)
388 s = socket.socket()
389 self.assertEqual(s.gettimeout(), None)
390 s.close()
391
392 # Check that setting it to an invalid value raises ValueError
393 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
394
395 # Check that setting it to an invalid type raises TypeError
396 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
397
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000398 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000399 if not hasattr(socket, 'inet_pton'):
400 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000401 from socket import inet_aton as f, inet_pton, AF_INET
402 g = lambda a: inet_pton(AF_INET, a)
403
Guido van Rossumb5b22702007-05-18 18:55:53 +0000404 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
405 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
406 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
407 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
408 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000409
Guido van Rossumb5b22702007-05-18 18:55:53 +0000410 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
411 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
412 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
413 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000414
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000415 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000416 if not hasattr(socket, 'inet_pton'):
417 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000418 try:
419 from socket import inet_pton, AF_INET6, has_ipv6
420 if not has_ipv6:
421 return
422 except ImportError:
423 return
424 f = lambda a: inet_pton(AF_INET6, a)
425
Guido van Rossum540d9872007-08-17 03:51:09 +0000426 self.assertEquals(b'\x00' * 16, f('::'))
427 self.assertEquals(b'\x00' * 16, f('0::0'))
428 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000429 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000430 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 +0000431 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
432 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000433
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000434 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000435 if not hasattr(socket, 'inet_ntop'):
436 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000437 from socket import inet_ntoa as f, inet_ntop, AF_INET
438 g = lambda a: inet_ntop(AF_INET, a)
439
Guido van Rossumb5b22702007-05-18 18:55:53 +0000440 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
441 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
442 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
443 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000444
Guido van Rossumb5b22702007-05-18 18:55:53 +0000445 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
446 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
447 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000448
449 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000450 if not hasattr(socket, 'inet_ntop'):
451 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000452 try:
453 from socket import inet_ntop, AF_INET6, has_ipv6
454 if not has_ipv6:
455 return
456 except ImportError:
457 return
458 f = lambda a: inet_ntop(AF_INET6, a)
459
Guido van Rossum540d9872007-08-17 03:51:09 +0000460 self.assertEquals('::', f(b'\x00' * 16))
461 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000462 self.assertEquals(
463 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000464 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 +0000465 )
466
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000467 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000468
Guido van Rossum24e4af82002-06-12 19:18:08 +0000469 def testSockName(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000470 # Testing getsockname(). Use a temporary socket to elicit an unused
471 # ephemeral port that we can use later in the test.
472 tempsock = socket.socket()
473 tempsock.bind(("0.0.0.0", 0))
474 (host, port) = tempsock.getsockname()
475 tempsock.close()
476 del tempsock
477
Guido van Rossum24e4af82002-06-12 19:18:08 +0000478 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000479 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000480 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000481 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
482 # it reasonable to get the host's addr in addition to 0.0.0.0.
483 # At least for eCos. This is required for the S/390 to pass.
484 my_ip_addr = socket.gethostbyname(socket.gethostname())
485 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000486 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000487
488 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000489 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000490 # We know a socket should start without reuse==0
491 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
492 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000493 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000494
495 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000496 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000497 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
498 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
499 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000500 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000501
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000502 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000503 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000504 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
505 sock.settimeout(1)
506 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000507 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000508
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509 def testNewAttributes(self):
510 # testing .family, .type and .protocol
511 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
512 self.assertEqual(sock.family, socket.AF_INET)
513 self.assertEqual(sock.type, socket.SOCK_STREAM)
514 self.assertEqual(sock.proto, 0)
515 sock.close()
516
Christian Heimesfaf2f632008-01-06 16:59:19 +0000517 def test_sock_ioctl(self):
518 if os.name != "nt":
519 return
520 self.assert_(hasattr(socket.socket, 'ioctl'))
521 self.assert_(hasattr(socket, 'SIO_RCVALL'))
522 self.assert_(hasattr(socket, 'RCVALL_ON'))
523 self.assert_(hasattr(socket, 'RCVALL_OFF'))
524
525
Guido van Rossum24e4af82002-06-12 19:18:08 +0000526class BasicTCPTest(SocketConnectedTest):
527
528 def __init__(self, methodName='runTest'):
529 SocketConnectedTest.__init__(self, methodName=methodName)
530
531 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000532 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000533 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000534 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000535
536 def _testRecv(self):
537 self.serv_conn.send(MSG)
538
539 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000540 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000541 seg1 = self.cli_conn.recv(len(MSG) - 3)
542 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000543 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000544 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000545
546 def _testOverFlowRecv(self):
547 self.serv_conn.send(MSG)
548
549 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000550 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000551 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000552 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000553
554 def _testRecvFrom(self):
555 self.serv_conn.send(MSG)
556
557 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000558 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000559 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
560 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000561 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000562 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000563
564 def _testOverFlowRecvFrom(self):
565 self.serv_conn.send(MSG)
566
567 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000568 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000569 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000570 while 1:
571 read = self.cli_conn.recv(1024)
572 if not read:
573 break
Guido van Rossume531e292002-08-08 20:28:34 +0000574 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000575 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000576
577 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000578 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000579 self.serv_conn.sendall(big_chunk)
580
581 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000582 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000583 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000584 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000585 fd = self.cli_conn.fileno()
586 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
587 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000588 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000589
590 def _testFromFd(self):
591 self.serv_conn.send(MSG)
592
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000593 def testDup(self):
594 # Testing dup()
595 sock = self.cli_conn.dup()
596 msg = sock.recv(1024)
597 self.assertEqual(msg, MSG)
598
599 def _testDup(self):
600 self.serv_conn.send(MSG)
601
Guido van Rossum24e4af82002-06-12 19:18:08 +0000602 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000603 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000604 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000605 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000606 # wait for _testShutdown to finish: on OS X, when the server
607 # closes the connection the client also becomes disconnected,
608 # and the client's shutdown call will fail. (Issue #4397.)
609 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000610
611 def _testShutdown(self):
612 self.serv_conn.send(MSG)
613 self.serv_conn.shutdown(2)
614
615class BasicUDPTest(ThreadedUDPSocketTest):
616
617 def __init__(self, methodName='runTest'):
618 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
619
620 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000621 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000622 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000623 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000624
625 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000626 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000627
Guido van Rossum1c938012002-06-12 21:17:20 +0000628 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000629 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000630 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000631 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000632
Guido van Rossum1c938012002-06-12 21:17:20 +0000633 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000634 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000635
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 def testRecvFromNegative(self):
637 # Negative lengths passed to recvfrom should give ValueError.
638 self.assertRaises(ValueError, self.serv.recvfrom, -1)
639
640 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000641 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643class TCPCloserTest(ThreadedTCPSocketTest):
644
645 def testClose(self):
646 conn, addr = self.serv.accept()
647 conn.close()
648
649 sd = self.cli
650 read, write, err = select.select([sd], [], [], 1.0)
651 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000652 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000654 # Calling close() many times should be safe.
655 conn.close()
656 conn.close()
657
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000659 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000660 time.sleep(1.0)
661
Dave Cole331708b2004-08-09 04:51:41 +0000662class BasicSocketPairTest(SocketPairTest):
663
664 def __init__(self, methodName='runTest'):
665 SocketPairTest.__init__(self, methodName=methodName)
666
667 def testRecv(self):
668 msg = self.serv.recv(1024)
669 self.assertEqual(msg, MSG)
670
671 def _testRecv(self):
672 self.cli.send(MSG)
673
674 def testSend(self):
675 self.serv.send(MSG)
676
677 def _testSend(self):
678 msg = self.cli.recv(1024)
679 self.assertEqual(msg, MSG)
680
Guido van Rossum24e4af82002-06-12 19:18:08 +0000681class NonBlockingTCPTests(ThreadedTCPSocketTest):
682
683 def __init__(self, methodName='runTest'):
684 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
685
686 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000687 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000688 self.serv.setblocking(0)
689 start = time.time()
690 try:
691 self.serv.accept()
692 except socket.error:
693 pass
694 end = time.time()
695 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
696
697 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000698 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000699
Guido van Rossum24e4af82002-06-12 19:18:08 +0000700 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000701 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000702 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000703 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000704 conn, addr = self.serv.accept()
705 except socket.error:
706 pass
707 else:
708 self.fail("Error trying to do non-blocking accept.")
709 read, write, err = select.select([self.serv], [], [])
710 if self.serv in read:
711 conn, addr = self.serv.accept()
712 else:
713 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000714
Guido van Rossum24e4af82002-06-12 19:18:08 +0000715 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000716 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000717 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000718
719 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000720 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721 conn, addr = self.serv.accept()
722
723 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000724 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000725 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000726
727 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000728 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000729 conn, addr = self.serv.accept()
730 conn.setblocking(0)
731 try:
732 msg = conn.recv(len(MSG))
733 except socket.error:
734 pass
735 else:
736 self.fail("Error trying to do non-blocking recv.")
737 read, write, err = select.select([conn], [], [])
738 if conn in read:
739 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000740 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000741 else:
742 self.fail("Error during select call to non-blocking socket.")
743
744 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000745 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000746 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000747 self.cli.send(MSG)
748
749class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000750 """Unit tests for the object returned by socket.makefile()
751
752 self.serv_file is the io object returned by makefile() on
753 the client connection. You can read from this file to
754 get output from the server.
755
756 self.cli_file is the io object returned by makefile() on the
757 server connection. You can write to this file to send output
758 to the client.
759 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000760
Guido van Rossume9f66142002-08-07 15:46:19 +0000761 bufsize = -1 # Use default buffer size
762
Guido van Rossum24e4af82002-06-12 19:18:08 +0000763 def __init__(self, methodName='runTest'):
764 SocketConnectedTest.__init__(self, methodName=methodName)
765
766 def setUp(self):
767 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000768 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000769
770 def tearDown(self):
771 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000772 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000773 self.serv_file = None
774 SocketConnectedTest.tearDown(self)
775
776 def clientSetUp(self):
777 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000778 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000779
780 def clientTearDown(self):
781 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000782 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000783 self.cli_file = None
784 SocketConnectedTest.clientTearDown(self)
785
786 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000787 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000788 first_seg = self.serv_file.read(len(MSG)-3)
789 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000790 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000791 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000792
793 def _testSmallRead(self):
794 self.cli_file.write(MSG)
795 self.cli_file.flush()
796
Guido van Rossum8c943832002-08-08 01:00:28 +0000797 def testFullRead(self):
798 # read until EOF
799 msg = self.serv_file.read()
800 self.assertEqual(msg, MSG)
801
802 def _testFullRead(self):
803 self.cli_file.write(MSG)
804 self.cli_file.close()
805
Guido van Rossum24e4af82002-06-12 19:18:08 +0000806 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000807 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000808 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000809 while 1:
810 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000811 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000812 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000813 buf += char
814 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000815
816 def _testUnbufferedRead(self):
817 self.cli_file.write(MSG)
818 self.cli_file.flush()
819
820 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000821 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000822 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000823 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000824
825 def _testReadline(self):
826 self.cli_file.write(MSG)
827 self.cli_file.flush()
828
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000829 def testCloseAfterMakefile(self):
830 # The file returned by makefile should keep the socket open.
831 self.cli_conn.close()
832 # read until EOF
833 msg = self.serv_file.read()
834 self.assertEqual(msg, MSG)
835
836 def _testCloseAfterMakefile(self):
837 self.cli_file.write(MSG)
838 self.cli_file.flush()
839
840 def testMakefileAfterMakefileClose(self):
841 self.serv_file.close()
842 msg = self.cli_conn.recv(len(MSG))
843 self.assertEqual(msg, MSG)
844
845 def _testMakefileAfterMakefileClose(self):
846 self.cli_file.write(MSG)
847 self.cli_file.flush()
848
Tim Peters116d83c2004-03-28 02:20:45 +0000849 def testClosedAttr(self):
850 self.assert_(not self.serv_file.closed)
851
852 def _testClosedAttr(self):
853 self.assert_(not self.cli_file.closed)
854
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000855 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000856 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000857 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
858
859 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000860 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000861 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
862
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000863 def testRealClose(self):
864 self.serv_file.close()
865 self.assertRaises(ValueError, self.serv_file.fileno)
866 self.cli_conn.close()
867 self.assertRaises(socket.error, self.cli_conn.getsockname)
868
869 def _testRealClose(self):
870 pass
871
872
Guido van Rossume9f66142002-08-07 15:46:19 +0000873class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
874
875 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000876
Guido van Rossume9f66142002-08-07 15:46:19 +0000877 In this case (and in this case only), it should be possible to
878 create a file object, read a line from it, create another file
879 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +0000880 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +0000881 when reading multiple requests from the same socket."""
882
883 bufsize = 0 # Use unbuffered mode
884
885 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000886 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000887 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000888 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000889 self.serv_file = self.cli_conn.makefile('rb', 0)
890 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000891 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000892
893 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000894 self.cli_file.write(b"A. " + MSG)
895 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000896 self.cli_file.flush()
897
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000898 def testMakefileClose(self):
899 # The file returned by makefile should keep the socket open...
900 self.cli_conn.close()
901 msg = self.cli_conn.recv(1024)
902 self.assertEqual(msg, MSG)
903 # ...until the file is itself closed
904 self.serv_file.close()
905 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
906
907 def _testMakefileClose(self):
908 self.cli_file.write(MSG)
909 self.cli_file.flush()
910
911 def testMakefileCloseSocketDestroy(self):
912 refcount_before = sys.getrefcount(self.cli_conn)
913 self.serv_file.close()
914 refcount_after = sys.getrefcount(self.cli_conn)
915 self.assertEqual(refcount_before - 1, refcount_after)
916
917 def _testMakefileCloseSocketDestroy(self):
918 pass
919
920
Guido van Rossum8c943832002-08-08 01:00:28 +0000921class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
922
923 bufsize = 1 # Default-buffered for reading; line-buffered for writing
924
925
926class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
927
928 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000929
Thomas Woutersb2137042007-02-01 18:02:27 +0000930
Guido van Rossumd8faa362007-04-27 19:54:29 +0000931class NetworkConnectionTest(object):
932 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000933
Guido van Rossumd8faa362007-04-27 19:54:29 +0000934 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000935 # We're inherited below by BasicTCPTest2, which also inherits
936 # BasicTCPTest, which defines self.port referenced below.
937 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000938 self.serv_conn = self.cli
939
940class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
941 """Tests that NetworkConnection does not break existing TCP functionality.
942 """
943
944class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000945
Guido van Rossumd8faa362007-04-27 19:54:29 +0000946 def testWithoutServer(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000947 port = support.find_unused_port()
Christian Heimes5e696852008-04-09 08:37:03 +0000948 self.failUnlessRaises(
949 socket.error,
950 lambda: socket.create_connection((HOST, port))
951 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952
953class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
954
955 def __init__(self, methodName='runTest'):
956 SocketTCPTest.__init__(self, methodName=methodName)
957 ThreadableTest.__init__(self)
958
959 def clientSetUp(self):
960 pass
961
962 def clientTearDown(self):
963 self.cli.close()
964 self.cli = None
965 ThreadableTest.clientTearDown(self)
966
967 def _justAccept(self):
968 conn, addr = self.serv.accept()
969
970 testFamily = _justAccept
971 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000972 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000973 self.assertEqual(self.cli.family, 2)
974
975 testTimeoutDefault = _justAccept
976 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000977 # passing no explicit timeout uses socket's global default
978 self.assert_(socket.getdefaulttimeout() is None)
979 socket.setdefaulttimeout(42)
980 try:
981 self.cli = socket.create_connection((HOST, self.port))
982 finally:
983 socket.setdefaulttimeout(None)
984 self.assertEquals(self.cli.gettimeout(), 42)
985
986 testTimeoutNone = _justAccept
987 def _testTimeoutNone(self):
988 # None timeout means the same as sock.settimeout(None)
989 self.assert_(socket.getdefaulttimeout() is None)
990 socket.setdefaulttimeout(30)
991 try:
992 self.cli = socket.create_connection((HOST, self.port), timeout=None)
993 finally:
994 socket.setdefaulttimeout(None)
995 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996
997 testTimeoutValueNamed = _justAccept
998 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000999 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001000 self.assertEqual(self.cli.gettimeout(), 30)
1001
1002 testTimeoutValueNonamed = _justAccept
1003 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001004 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005 self.assertEqual(self.cli.gettimeout(), 30)
1006
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1008
1009 def __init__(self, methodName='runTest'):
1010 SocketTCPTest.__init__(self, methodName=methodName)
1011 ThreadableTest.__init__(self)
1012
1013 def clientSetUp(self):
1014 pass
1015
1016 def clientTearDown(self):
1017 self.cli.close()
1018 self.cli = None
1019 ThreadableTest.clientTearDown(self)
1020
1021 def testInsideTimeout(self):
1022 conn, addr = self.serv.accept()
1023 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001024 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025 testOutsideTimeout = testInsideTimeout
1026
1027 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001028 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001030 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001033 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
1035
1036
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001037class TCPTimeoutTest(SocketTCPTest):
1038
1039 def testTCPTimeout(self):
1040 def raise_timeout(*args, **kwargs):
1041 self.serv.settimeout(1.0)
1042 self.serv.accept()
1043 self.failUnlessRaises(socket.timeout, raise_timeout,
1044 "Error generating a timeout exception (TCP)")
1045
1046 def testTimeoutZero(self):
1047 ok = False
1048 try:
1049 self.serv.settimeout(0.0)
1050 foo = self.serv.accept()
1051 except socket.timeout:
1052 self.fail("caught timeout instead of error (TCP)")
1053 except socket.error:
1054 ok = True
1055 except:
1056 self.fail("caught unexpected exception (TCP)")
1057 if not ok:
1058 self.fail("accept() returned success when we did not expect it")
1059
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001060 def testInterruptedTimeout(self):
1061 # XXX I don't know how to do this test on MSWindows or any other
1062 # plaform that doesn't support signal.alarm() or os.kill(), though
1063 # the bug should have existed on all platforms.
1064 if not hasattr(signal, "alarm"):
1065 return # can only test on *nix
1066 self.serv.settimeout(5.0) # must be longer than alarm
1067 class Alarm(Exception):
1068 pass
1069 def alarm_handler(signal, frame):
1070 raise Alarm
1071 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1072 try:
1073 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1074 try:
1075 foo = self.serv.accept()
1076 except socket.timeout:
1077 self.fail("caught timeout instead of Alarm")
1078 except Alarm:
1079 pass
1080 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001081 self.fail("caught other exception instead of Alarm:"
1082 " %s(%s):\n%s" %
1083 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084 else:
1085 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001086 finally:
1087 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001088 except Alarm:
1089 self.fail("got Alarm in wrong place")
1090 finally:
1091 # no alarm can be pending. Safe to restore old handler.
1092 signal.signal(signal.SIGALRM, old_alarm)
1093
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001094class UDPTimeoutTest(SocketTCPTest):
1095
1096 def testUDPTimeout(self):
1097 def raise_timeout(*args, **kwargs):
1098 self.serv.settimeout(1.0)
1099 self.serv.recv(1024)
1100 self.failUnlessRaises(socket.timeout, raise_timeout,
1101 "Error generating a timeout exception (UDP)")
1102
1103 def testTimeoutZero(self):
1104 ok = False
1105 try:
1106 self.serv.settimeout(0.0)
1107 foo = self.serv.recv(1024)
1108 except socket.timeout:
1109 self.fail("caught timeout instead of error (UDP)")
1110 except socket.error:
1111 ok = True
1112 except:
1113 self.fail("caught unexpected exception (UDP)")
1114 if not ok:
1115 self.fail("recv() returned success when we did not expect it")
1116
1117class TestExceptions(unittest.TestCase):
1118
1119 def testExceptionTree(self):
1120 self.assert_(issubclass(socket.error, Exception))
1121 self.assert_(issubclass(socket.herror, socket.error))
1122 self.assert_(issubclass(socket.gaierror, socket.error))
1123 self.assert_(issubclass(socket.timeout, socket.error))
1124
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125class TestLinuxAbstractNamespace(unittest.TestCase):
1126
1127 UNIX_PATH_MAX = 108
1128
1129 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001130 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1132 s1.bind(address)
1133 s1.listen(1)
1134 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1135 s2.connect(s1.getsockname())
1136 s1.accept()
1137 self.assertEqual(s1.getsockname(), address)
1138 self.assertEqual(s2.getpeername(), address)
1139
1140 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001141 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1143 s.bind(address)
1144 self.assertEqual(s.getsockname(), address)
1145
1146 def testNameOverflow(self):
1147 address = "\x00" + "h" * self.UNIX_PATH_MAX
1148 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1149 self.assertRaises(socket.error, s.bind, address)
1150
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001151
Thomas Wouters477c8d52006-05-27 19:21:47 +00001152class BufferIOTest(SocketConnectedTest):
1153 """
1154 Test the buffer versions of socket.recv() and socket.send().
1155 """
1156 def __init__(self, methodName='runTest'):
1157 SocketConnectedTest.__init__(self, methodName=methodName)
1158
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001159 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001160 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001161 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001162 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001163 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001164 self.assertEqual(msg, MSG)
1165
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001166 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001167 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001168 self.serv_conn.send(buf)
1169
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001170 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001171 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001172 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001174 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175 self.assertEqual(msg, MSG)
1176
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001177 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001178 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001179 self.serv_conn.send(buf)
1180
Christian Heimes043d6f62008-01-07 17:19:16 +00001181
1182TIPC_STYPE = 2000
1183TIPC_LOWER = 200
1184TIPC_UPPER = 210
1185
1186def isTipcAvailable():
1187 """Check if the TIPC module is loaded
1188
1189 The TIPC module is not loaded automatically on Ubuntu and probably
1190 other Linux distros.
1191 """
1192 if not hasattr(socket, "AF_TIPC"):
1193 return False
1194 if not os.path.isfile("/proc/modules"):
1195 return False
1196 with open("/proc/modules") as f:
1197 for line in f:
1198 if line.startswith("tipc "):
1199 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001200 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001201 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1202 return False
1203
1204class TIPCTest (unittest.TestCase):
1205 def testRDM(self):
1206 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1207 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1208
1209 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1210 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1211 TIPC_LOWER, TIPC_UPPER)
1212 srv.bind(srvaddr)
1213
1214 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1215 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1216 cli.sendto(MSG, sendaddr)
1217
1218 msg, recvaddr = srv.recvfrom(1024)
1219
1220 self.assertEqual(cli.getsockname(), recvaddr)
1221 self.assertEqual(msg, MSG)
1222
1223
1224class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1225 def __init__(self, methodName = 'runTest'):
1226 unittest.TestCase.__init__(self, methodName = methodName)
1227 ThreadableTest.__init__(self)
1228
1229 def setUp(self):
1230 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1231 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1232 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1233 TIPC_LOWER, TIPC_UPPER)
1234 self.srv.bind(srvaddr)
1235 self.srv.listen(5)
1236 self.serverExplicitReady()
1237 self.conn, self.connaddr = self.srv.accept()
1238
1239 def clientSetUp(self):
1240 # The is a hittable race between serverExplicitReady() and the
1241 # accept() call; sleep a little while to avoid it, otherwise
1242 # we could get an exception
1243 time.sleep(0.1)
1244 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1245 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1246 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1247 self.cli.connect(addr)
1248 self.cliaddr = self.cli.getsockname()
1249
1250 def testStream(self):
1251 msg = self.conn.recv(1024)
1252 self.assertEqual(msg, MSG)
1253 self.assertEqual(self.cliaddr, self.connaddr)
1254
1255 def _testStream(self):
1256 self.cli.send(MSG)
1257 self.cli.close()
1258
1259
Guido van Rossumb995eb72002-07-31 16:08:40 +00001260def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001261 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001263 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001264 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001265
1266 tests.extend([
1267 NonBlockingTCPTests,
1268 FileObjectClassTestCase,
1269 UnbufferedFileObjectClassTestCase,
1270 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001271 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272 NetworkConnectionNoServer,
1273 NetworkConnectionAttributesTest,
1274 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001275 ])
Dave Cole331708b2004-08-09 04:51:41 +00001276 if hasattr(socket, "socketpair"):
1277 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001278 if sys.platform == 'linux2':
1279 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001280 if isTipcAvailable():
1281 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001282 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001283
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001284 thread_info = support.threading_setup()
1285 support.run_unittest(*tests)
1286 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001287
1288if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001289 test_main()