blob: b0fe0577717e8c274250f3e86adfd9303fb72a8c [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)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000606
607 def _testShutdown(self):
608 self.serv_conn.send(MSG)
609 self.serv_conn.shutdown(2)
610
611class BasicUDPTest(ThreadedUDPSocketTest):
612
613 def __init__(self, methodName='runTest'):
614 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
615
616 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000617 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000618 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000619 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000620
621 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000622 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000623
Guido van Rossum1c938012002-06-12 21:17:20 +0000624 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000625 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000626 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000627 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000628
Guido van Rossum1c938012002-06-12 21:17:20 +0000629 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000630 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000631
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632 def testRecvFromNegative(self):
633 # Negative lengths passed to recvfrom should give ValueError.
634 self.assertRaises(ValueError, self.serv.recvfrom, -1)
635
636 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000637 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639class TCPCloserTest(ThreadedTCPSocketTest):
640
641 def testClose(self):
642 conn, addr = self.serv.accept()
643 conn.close()
644
645 sd = self.cli
646 read, write, err = select.select([sd], [], [], 1.0)
647 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000648 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000650 # Calling close() many times should be safe.
651 conn.close()
652 conn.close()
653
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000654 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000655 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000656 time.sleep(1.0)
657
Dave Cole331708b2004-08-09 04:51:41 +0000658class BasicSocketPairTest(SocketPairTest):
659
660 def __init__(self, methodName='runTest'):
661 SocketPairTest.__init__(self, methodName=methodName)
662
663 def testRecv(self):
664 msg = self.serv.recv(1024)
665 self.assertEqual(msg, MSG)
666
667 def _testRecv(self):
668 self.cli.send(MSG)
669
670 def testSend(self):
671 self.serv.send(MSG)
672
673 def _testSend(self):
674 msg = self.cli.recv(1024)
675 self.assertEqual(msg, MSG)
676
Guido van Rossum24e4af82002-06-12 19:18:08 +0000677class NonBlockingTCPTests(ThreadedTCPSocketTest):
678
679 def __init__(self, methodName='runTest'):
680 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
681
682 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000683 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000684 self.serv.setblocking(0)
685 start = time.time()
686 try:
687 self.serv.accept()
688 except socket.error:
689 pass
690 end = time.time()
691 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
692
693 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000694 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000695
Guido van Rossum24e4af82002-06-12 19:18:08 +0000696 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000697 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000698 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000699 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000700 conn, addr = self.serv.accept()
701 except socket.error:
702 pass
703 else:
704 self.fail("Error trying to do non-blocking accept.")
705 read, write, err = select.select([self.serv], [], [])
706 if self.serv in read:
707 conn, addr = self.serv.accept()
708 else:
709 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000710
Guido van Rossum24e4af82002-06-12 19:18:08 +0000711 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000712 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000713 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000714
715 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000716 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000717 conn, addr = self.serv.accept()
718
719 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000720 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000721 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000722
723 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000724 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000725 conn, addr = self.serv.accept()
726 conn.setblocking(0)
727 try:
728 msg = conn.recv(len(MSG))
729 except socket.error:
730 pass
731 else:
732 self.fail("Error trying to do non-blocking recv.")
733 read, write, err = select.select([conn], [], [])
734 if conn in read:
735 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000736 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000737 else:
738 self.fail("Error during select call to non-blocking socket.")
739
740 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000741 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000742 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000743 self.cli.send(MSG)
744
745class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000746 """Unit tests for the object returned by socket.makefile()
747
748 self.serv_file is the io object returned by makefile() on
749 the client connection. You can read from this file to
750 get output from the server.
751
752 self.cli_file is the io object returned by makefile() on the
753 server connection. You can write to this file to send output
754 to the client.
755 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000756
Guido van Rossume9f66142002-08-07 15:46:19 +0000757 bufsize = -1 # Use default buffer size
758
Guido van Rossum24e4af82002-06-12 19:18:08 +0000759 def __init__(self, methodName='runTest'):
760 SocketConnectedTest.__init__(self, methodName=methodName)
761
762 def setUp(self):
763 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000764 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000765
766 def tearDown(self):
767 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000768 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000769 self.serv_file = None
770 SocketConnectedTest.tearDown(self)
771
772 def clientSetUp(self):
773 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000774 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000775
776 def clientTearDown(self):
777 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000778 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000779 self.cli_file = None
780 SocketConnectedTest.clientTearDown(self)
781
782 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000783 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000784 first_seg = self.serv_file.read(len(MSG)-3)
785 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000786 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000787 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000788
789 def _testSmallRead(self):
790 self.cli_file.write(MSG)
791 self.cli_file.flush()
792
Guido van Rossum8c943832002-08-08 01:00:28 +0000793 def testFullRead(self):
794 # read until EOF
795 msg = self.serv_file.read()
796 self.assertEqual(msg, MSG)
797
798 def _testFullRead(self):
799 self.cli_file.write(MSG)
800 self.cli_file.close()
801
Guido van Rossum24e4af82002-06-12 19:18:08 +0000802 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000803 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000804 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000805 while 1:
806 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000807 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000808 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000809 buf += char
810 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000811
812 def _testUnbufferedRead(self):
813 self.cli_file.write(MSG)
814 self.cli_file.flush()
815
816 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000817 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000818 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000819 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000820
821 def _testReadline(self):
822 self.cli_file.write(MSG)
823 self.cli_file.flush()
824
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000825 def testCloseAfterMakefile(self):
826 # The file returned by makefile should keep the socket open.
827 self.cli_conn.close()
828 # read until EOF
829 msg = self.serv_file.read()
830 self.assertEqual(msg, MSG)
831
832 def _testCloseAfterMakefile(self):
833 self.cli_file.write(MSG)
834 self.cli_file.flush()
835
836 def testMakefileAfterMakefileClose(self):
837 self.serv_file.close()
838 msg = self.cli_conn.recv(len(MSG))
839 self.assertEqual(msg, MSG)
840
841 def _testMakefileAfterMakefileClose(self):
842 self.cli_file.write(MSG)
843 self.cli_file.flush()
844
Tim Peters116d83c2004-03-28 02:20:45 +0000845 def testClosedAttr(self):
846 self.assert_(not self.serv_file.closed)
847
848 def _testClosedAttr(self):
849 self.assert_(not self.cli_file.closed)
850
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000851 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000852 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000853 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
854
855 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000856 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000857 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
858
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000859 def testRealClose(self):
860 self.serv_file.close()
861 self.assertRaises(ValueError, self.serv_file.fileno)
862 self.cli_conn.close()
863 self.assertRaises(socket.error, self.cli_conn.getsockname)
864
865 def _testRealClose(self):
866 pass
867
868
Guido van Rossume9f66142002-08-07 15:46:19 +0000869class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
870
871 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000872
Guido van Rossume9f66142002-08-07 15:46:19 +0000873 In this case (and in this case only), it should be possible to
874 create a file object, read a line from it, create another file
875 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +0000876 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +0000877 when reading multiple requests from the same socket."""
878
879 bufsize = 0 # Use unbuffered mode
880
881 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000882 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000883 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000884 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000885 self.serv_file = self.cli_conn.makefile('rb', 0)
886 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000887 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000888
889 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000890 self.cli_file.write(b"A. " + MSG)
891 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000892 self.cli_file.flush()
893
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000894 def testMakefileClose(self):
895 # The file returned by makefile should keep the socket open...
896 self.cli_conn.close()
897 msg = self.cli_conn.recv(1024)
898 self.assertEqual(msg, MSG)
899 # ...until the file is itself closed
900 self.serv_file.close()
901 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
902
903 def _testMakefileClose(self):
904 self.cli_file.write(MSG)
905 self.cli_file.flush()
906
907 def testMakefileCloseSocketDestroy(self):
908 refcount_before = sys.getrefcount(self.cli_conn)
909 self.serv_file.close()
910 refcount_after = sys.getrefcount(self.cli_conn)
911 self.assertEqual(refcount_before - 1, refcount_after)
912
913 def _testMakefileCloseSocketDestroy(self):
914 pass
915
916
Guido van Rossum8c943832002-08-08 01:00:28 +0000917class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
918
919 bufsize = 1 # Default-buffered for reading; line-buffered for writing
920
921
922class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
923
924 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000925
Thomas Woutersb2137042007-02-01 18:02:27 +0000926
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927class NetworkConnectionTest(object):
928 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000929
Guido van Rossumd8faa362007-04-27 19:54:29 +0000930 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000931 # We're inherited below by BasicTCPTest2, which also inherits
932 # BasicTCPTest, which defines self.port referenced below.
933 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000934 self.serv_conn = self.cli
935
936class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
937 """Tests that NetworkConnection does not break existing TCP functionality.
938 """
939
940class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000941
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 def testWithoutServer(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000943 port = support.find_unused_port()
Christian Heimes5e696852008-04-09 08:37:03 +0000944 self.failUnlessRaises(
945 socket.error,
946 lambda: socket.create_connection((HOST, port))
947 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948
949class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
950
951 def __init__(self, methodName='runTest'):
952 SocketTCPTest.__init__(self, methodName=methodName)
953 ThreadableTest.__init__(self)
954
955 def clientSetUp(self):
956 pass
957
958 def clientTearDown(self):
959 self.cli.close()
960 self.cli = None
961 ThreadableTest.clientTearDown(self)
962
963 def _justAccept(self):
964 conn, addr = self.serv.accept()
965
966 testFamily = _justAccept
967 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000968 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 self.assertEqual(self.cli.family, 2)
970
971 testTimeoutDefault = _justAccept
972 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000973 # passing no explicit timeout uses socket's global default
974 self.assert_(socket.getdefaulttimeout() is None)
975 socket.setdefaulttimeout(42)
976 try:
977 self.cli = socket.create_connection((HOST, self.port))
978 finally:
979 socket.setdefaulttimeout(None)
980 self.assertEquals(self.cli.gettimeout(), 42)
981
982 testTimeoutNone = _justAccept
983 def _testTimeoutNone(self):
984 # None timeout means the same as sock.settimeout(None)
985 self.assert_(socket.getdefaulttimeout() is None)
986 socket.setdefaulttimeout(30)
987 try:
988 self.cli = socket.create_connection((HOST, self.port), timeout=None)
989 finally:
990 socket.setdefaulttimeout(None)
991 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000992
993 testTimeoutValueNamed = _justAccept
994 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000995 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 self.assertEqual(self.cli.gettimeout(), 30)
997
998 testTimeoutValueNonamed = _justAccept
999 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001000 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001 self.assertEqual(self.cli.gettimeout(), 30)
1002
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1004
1005 def __init__(self, methodName='runTest'):
1006 SocketTCPTest.__init__(self, methodName=methodName)
1007 ThreadableTest.__init__(self)
1008
1009 def clientSetUp(self):
1010 pass
1011
1012 def clientTearDown(self):
1013 self.cli.close()
1014 self.cli = None
1015 ThreadableTest.clientTearDown(self)
1016
1017 def testInsideTimeout(self):
1018 conn, addr = self.serv.accept()
1019 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001020 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 testOutsideTimeout = testInsideTimeout
1022
1023 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001024 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001026 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001027
1028 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001029 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
1031
1032
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001033class TCPTimeoutTest(SocketTCPTest):
1034
1035 def testTCPTimeout(self):
1036 def raise_timeout(*args, **kwargs):
1037 self.serv.settimeout(1.0)
1038 self.serv.accept()
1039 self.failUnlessRaises(socket.timeout, raise_timeout,
1040 "Error generating a timeout exception (TCP)")
1041
1042 def testTimeoutZero(self):
1043 ok = False
1044 try:
1045 self.serv.settimeout(0.0)
1046 foo = self.serv.accept()
1047 except socket.timeout:
1048 self.fail("caught timeout instead of error (TCP)")
1049 except socket.error:
1050 ok = True
1051 except:
1052 self.fail("caught unexpected exception (TCP)")
1053 if not ok:
1054 self.fail("accept() returned success when we did not expect it")
1055
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001056 def testInterruptedTimeout(self):
1057 # XXX I don't know how to do this test on MSWindows or any other
1058 # plaform that doesn't support signal.alarm() or os.kill(), though
1059 # the bug should have existed on all platforms.
1060 if not hasattr(signal, "alarm"):
1061 return # can only test on *nix
1062 self.serv.settimeout(5.0) # must be longer than alarm
1063 class Alarm(Exception):
1064 pass
1065 def alarm_handler(signal, frame):
1066 raise Alarm
1067 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1068 try:
1069 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1070 try:
1071 foo = self.serv.accept()
1072 except socket.timeout:
1073 self.fail("caught timeout instead of Alarm")
1074 except Alarm:
1075 pass
1076 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001077 self.fail("caught other exception instead of Alarm:"
1078 " %s(%s):\n%s" %
1079 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001080 else:
1081 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001082 finally:
1083 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084 except Alarm:
1085 self.fail("got Alarm in wrong place")
1086 finally:
1087 # no alarm can be pending. Safe to restore old handler.
1088 signal.signal(signal.SIGALRM, old_alarm)
1089
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001090class UDPTimeoutTest(SocketTCPTest):
1091
1092 def testUDPTimeout(self):
1093 def raise_timeout(*args, **kwargs):
1094 self.serv.settimeout(1.0)
1095 self.serv.recv(1024)
1096 self.failUnlessRaises(socket.timeout, raise_timeout,
1097 "Error generating a timeout exception (UDP)")
1098
1099 def testTimeoutZero(self):
1100 ok = False
1101 try:
1102 self.serv.settimeout(0.0)
1103 foo = self.serv.recv(1024)
1104 except socket.timeout:
1105 self.fail("caught timeout instead of error (UDP)")
1106 except socket.error:
1107 ok = True
1108 except:
1109 self.fail("caught unexpected exception (UDP)")
1110 if not ok:
1111 self.fail("recv() returned success when we did not expect it")
1112
1113class TestExceptions(unittest.TestCase):
1114
1115 def testExceptionTree(self):
1116 self.assert_(issubclass(socket.error, Exception))
1117 self.assert_(issubclass(socket.herror, socket.error))
1118 self.assert_(issubclass(socket.gaierror, socket.error))
1119 self.assert_(issubclass(socket.timeout, socket.error))
1120
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001121class TestLinuxAbstractNamespace(unittest.TestCase):
1122
1123 UNIX_PATH_MAX = 108
1124
1125 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001126 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001127 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1128 s1.bind(address)
1129 s1.listen(1)
1130 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1131 s2.connect(s1.getsockname())
1132 s1.accept()
1133 self.assertEqual(s1.getsockname(), address)
1134 self.assertEqual(s2.getpeername(), address)
1135
1136 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001137 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1139 s.bind(address)
1140 self.assertEqual(s.getsockname(), address)
1141
1142 def testNameOverflow(self):
1143 address = "\x00" + "h" * self.UNIX_PATH_MAX
1144 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1145 self.assertRaises(socket.error, s.bind, address)
1146
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001147
Thomas Wouters477c8d52006-05-27 19:21:47 +00001148class BufferIOTest(SocketConnectedTest):
1149 """
1150 Test the buffer versions of socket.recv() and socket.send().
1151 """
1152 def __init__(self, methodName='runTest'):
1153 SocketConnectedTest.__init__(self, methodName=methodName)
1154
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001155 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001156 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001157 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001159 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160 self.assertEqual(msg, MSG)
1161
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001162 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001163 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001164 self.serv_conn.send(buf)
1165
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001166 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001167 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001168 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001170 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001171 self.assertEqual(msg, MSG)
1172
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001173 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001174 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175 self.serv_conn.send(buf)
1176
Christian Heimes043d6f62008-01-07 17:19:16 +00001177
1178TIPC_STYPE = 2000
1179TIPC_LOWER = 200
1180TIPC_UPPER = 210
1181
1182def isTipcAvailable():
1183 """Check if the TIPC module is loaded
1184
1185 The TIPC module is not loaded automatically on Ubuntu and probably
1186 other Linux distros.
1187 """
1188 if not hasattr(socket, "AF_TIPC"):
1189 return False
1190 if not os.path.isfile("/proc/modules"):
1191 return False
1192 with open("/proc/modules") as f:
1193 for line in f:
1194 if line.startswith("tipc "):
1195 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001196 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001197 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1198 return False
1199
1200class TIPCTest (unittest.TestCase):
1201 def testRDM(self):
1202 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1203 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1204
1205 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1206 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1207 TIPC_LOWER, TIPC_UPPER)
1208 srv.bind(srvaddr)
1209
1210 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1211 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1212 cli.sendto(MSG, sendaddr)
1213
1214 msg, recvaddr = srv.recvfrom(1024)
1215
1216 self.assertEqual(cli.getsockname(), recvaddr)
1217 self.assertEqual(msg, MSG)
1218
1219
1220class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1221 def __init__(self, methodName = 'runTest'):
1222 unittest.TestCase.__init__(self, methodName = methodName)
1223 ThreadableTest.__init__(self)
1224
1225 def setUp(self):
1226 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1227 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1228 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1229 TIPC_LOWER, TIPC_UPPER)
1230 self.srv.bind(srvaddr)
1231 self.srv.listen(5)
1232 self.serverExplicitReady()
1233 self.conn, self.connaddr = self.srv.accept()
1234
1235 def clientSetUp(self):
1236 # The is a hittable race between serverExplicitReady() and the
1237 # accept() call; sleep a little while to avoid it, otherwise
1238 # we could get an exception
1239 time.sleep(0.1)
1240 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1241 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1242 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1243 self.cli.connect(addr)
1244 self.cliaddr = self.cli.getsockname()
1245
1246 def testStream(self):
1247 msg = self.conn.recv(1024)
1248 self.assertEqual(msg, MSG)
1249 self.assertEqual(self.cliaddr, self.connaddr)
1250
1251 def _testStream(self):
1252 self.cli.send(MSG)
1253 self.cli.close()
1254
1255
Guido van Rossumb995eb72002-07-31 16:08:40 +00001256def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001257 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001258 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001259 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001260 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001261
1262 tests.extend([
1263 NonBlockingTCPTests,
1264 FileObjectClassTestCase,
1265 UnbufferedFileObjectClassTestCase,
1266 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001267 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001268 NetworkConnectionNoServer,
1269 NetworkConnectionAttributesTest,
1270 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001271 ])
Dave Cole331708b2004-08-09 04:51:41 +00001272 if hasattr(socket, "socketpair"):
1273 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274 if sys.platform == 'linux2':
1275 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001276 if isTipcAvailable():
1277 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001278 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001279
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001280 thread_info = support.threading_setup()
1281 support.run_unittest(*tests)
1282 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001283
1284if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001285 test_main()