blob: 9d753b7ea53c3596f6e1a33ab191fafce61ac6d6 [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
Guido van Rossume9f66142002-08-07 15:46:19 +0000851class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
852
853 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000854
Guido van Rossume9f66142002-08-07 15:46:19 +0000855 In this case (and in this case only), it should be possible to
856 create a file object, read a line from it, create another file
857 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +0000858 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +0000859 when reading multiple requests from the same socket."""
860
861 bufsize = 0 # Use unbuffered mode
862
863 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000864 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000865 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000866 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000867 self.serv_file = self.cli_conn.makefile('rb', 0)
868 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000869 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000870
871 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000872 self.cli_file.write(b"A. " + MSG)
873 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000874 self.cli_file.flush()
875
Guido van Rossum8c943832002-08-08 01:00:28 +0000876class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
877
878 bufsize = 1 # Default-buffered for reading; line-buffered for writing
879
880
881class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
882
883 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000884
Thomas Woutersb2137042007-02-01 18:02:27 +0000885
Guido van Rossumd8faa362007-04-27 19:54:29 +0000886class NetworkConnectionTest(object):
887 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000888
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000890 # We're inherited below by BasicTCPTest2, which also inherits
891 # BasicTCPTest, which defines self.port referenced below.
892 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000893 self.serv_conn = self.cli
894
895class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
896 """Tests that NetworkConnection does not break existing TCP functionality.
897 """
898
899class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000900
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 def testWithoutServer(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000902 port = support.find_unused_port()
Christian Heimes5e696852008-04-09 08:37:03 +0000903 self.failUnlessRaises(
904 socket.error,
905 lambda: socket.create_connection((HOST, port))
906 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
909
910 def __init__(self, methodName='runTest'):
911 SocketTCPTest.__init__(self, methodName=methodName)
912 ThreadableTest.__init__(self)
913
914 def clientSetUp(self):
915 pass
916
917 def clientTearDown(self):
918 self.cli.close()
919 self.cli = None
920 ThreadableTest.clientTearDown(self)
921
922 def _justAccept(self):
923 conn, addr = self.serv.accept()
924
925 testFamily = _justAccept
926 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000927 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 self.assertEqual(self.cli.family, 2)
929
930 testTimeoutDefault = _justAccept
931 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000932 # passing no explicit timeout uses socket's global default
933 self.assert_(socket.getdefaulttimeout() is None)
934 socket.setdefaulttimeout(42)
935 try:
936 self.cli = socket.create_connection((HOST, self.port))
937 finally:
938 socket.setdefaulttimeout(None)
939 self.assertEquals(self.cli.gettimeout(), 42)
940
941 testTimeoutNone = _justAccept
942 def _testTimeoutNone(self):
943 # None timeout means the same as sock.settimeout(None)
944 self.assert_(socket.getdefaulttimeout() is None)
945 socket.setdefaulttimeout(30)
946 try:
947 self.cli = socket.create_connection((HOST, self.port), timeout=None)
948 finally:
949 socket.setdefaulttimeout(None)
950 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952 testTimeoutValueNamed = _justAccept
953 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000954 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955 self.assertEqual(self.cli.gettimeout(), 30)
956
957 testTimeoutValueNonamed = _justAccept
958 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000959 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960 self.assertEqual(self.cli.gettimeout(), 30)
961
Guido van Rossumd8faa362007-04-27 19:54:29 +0000962class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
963
964 def __init__(self, methodName='runTest'):
965 SocketTCPTest.__init__(self, methodName=methodName)
966 ThreadableTest.__init__(self)
967
968 def clientSetUp(self):
969 pass
970
971 def clientTearDown(self):
972 self.cli.close()
973 self.cli = None
974 ThreadableTest.clientTearDown(self)
975
976 def testInsideTimeout(self):
977 conn, addr = self.serv.accept()
978 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000979 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980 testOutsideTimeout = testInsideTimeout
981
982 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000983 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000985 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000986
987 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000988 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
990
991
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000992class TCPTimeoutTest(SocketTCPTest):
993
994 def testTCPTimeout(self):
995 def raise_timeout(*args, **kwargs):
996 self.serv.settimeout(1.0)
997 self.serv.accept()
998 self.failUnlessRaises(socket.timeout, raise_timeout,
999 "Error generating a timeout exception (TCP)")
1000
1001 def testTimeoutZero(self):
1002 ok = False
1003 try:
1004 self.serv.settimeout(0.0)
1005 foo = self.serv.accept()
1006 except socket.timeout:
1007 self.fail("caught timeout instead of error (TCP)")
1008 except socket.error:
1009 ok = True
1010 except:
1011 self.fail("caught unexpected exception (TCP)")
1012 if not ok:
1013 self.fail("accept() returned success when we did not expect it")
1014
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015 def testInterruptedTimeout(self):
1016 # XXX I don't know how to do this test on MSWindows or any other
1017 # plaform that doesn't support signal.alarm() or os.kill(), though
1018 # the bug should have existed on all platforms.
1019 if not hasattr(signal, "alarm"):
1020 return # can only test on *nix
1021 self.serv.settimeout(5.0) # must be longer than alarm
1022 class Alarm(Exception):
1023 pass
1024 def alarm_handler(signal, frame):
1025 raise Alarm
1026 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1027 try:
1028 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1029 try:
1030 foo = self.serv.accept()
1031 except socket.timeout:
1032 self.fail("caught timeout instead of Alarm")
1033 except Alarm:
1034 pass
1035 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001036 self.fail("caught other exception instead of Alarm:"
1037 " %s(%s):\n%s" %
1038 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001039 else:
1040 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001041 finally:
1042 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001043 except Alarm:
1044 self.fail("got Alarm in wrong place")
1045 finally:
1046 # no alarm can be pending. Safe to restore old handler.
1047 signal.signal(signal.SIGALRM, old_alarm)
1048
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001049class UDPTimeoutTest(SocketTCPTest):
1050
1051 def testUDPTimeout(self):
1052 def raise_timeout(*args, **kwargs):
1053 self.serv.settimeout(1.0)
1054 self.serv.recv(1024)
1055 self.failUnlessRaises(socket.timeout, raise_timeout,
1056 "Error generating a timeout exception (UDP)")
1057
1058 def testTimeoutZero(self):
1059 ok = False
1060 try:
1061 self.serv.settimeout(0.0)
1062 foo = self.serv.recv(1024)
1063 except socket.timeout:
1064 self.fail("caught timeout instead of error (UDP)")
1065 except socket.error:
1066 ok = True
1067 except:
1068 self.fail("caught unexpected exception (UDP)")
1069 if not ok:
1070 self.fail("recv() returned success when we did not expect it")
1071
1072class TestExceptions(unittest.TestCase):
1073
1074 def testExceptionTree(self):
1075 self.assert_(issubclass(socket.error, Exception))
1076 self.assert_(issubclass(socket.herror, socket.error))
1077 self.assert_(issubclass(socket.gaierror, socket.error))
1078 self.assert_(issubclass(socket.timeout, socket.error))
1079
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001080class TestLinuxAbstractNamespace(unittest.TestCase):
1081
1082 UNIX_PATH_MAX = 108
1083
1084 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001085 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001086 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1087 s1.bind(address)
1088 s1.listen(1)
1089 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1090 s2.connect(s1.getsockname())
1091 s1.accept()
1092 self.assertEqual(s1.getsockname(), address)
1093 self.assertEqual(s2.getpeername(), address)
1094
1095 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001096 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001097 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1098 s.bind(address)
1099 self.assertEqual(s.getsockname(), address)
1100
1101 def testNameOverflow(self):
1102 address = "\x00" + "h" * self.UNIX_PATH_MAX
1103 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1104 self.assertRaises(socket.error, s.bind, address)
1105
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001106
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107class BufferIOTest(SocketConnectedTest):
1108 """
1109 Test the buffer versions of socket.recv() and socket.send().
1110 """
1111 def __init__(self, methodName='runTest'):
1112 SocketConnectedTest.__init__(self, methodName=methodName)
1113
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001114 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001115 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001116 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001118 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119 self.assertEqual(msg, MSG)
1120
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001121 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001122 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 self.serv_conn.send(buf)
1124
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001125 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001126 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001127 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001129 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001130 self.assertEqual(msg, MSG)
1131
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001132 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001133 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001134 self.serv_conn.send(buf)
1135
Christian Heimes043d6f62008-01-07 17:19:16 +00001136
1137TIPC_STYPE = 2000
1138TIPC_LOWER = 200
1139TIPC_UPPER = 210
1140
1141def isTipcAvailable():
1142 """Check if the TIPC module is loaded
1143
1144 The TIPC module is not loaded automatically on Ubuntu and probably
1145 other Linux distros.
1146 """
1147 if not hasattr(socket, "AF_TIPC"):
1148 return False
1149 if not os.path.isfile("/proc/modules"):
1150 return False
1151 with open("/proc/modules") as f:
1152 for line in f:
1153 if line.startswith("tipc "):
1154 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001155 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001156 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1157 return False
1158
1159class TIPCTest (unittest.TestCase):
1160 def testRDM(self):
1161 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1162 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1163
1164 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1165 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1166 TIPC_LOWER, TIPC_UPPER)
1167 srv.bind(srvaddr)
1168
1169 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1170 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1171 cli.sendto(MSG, sendaddr)
1172
1173 msg, recvaddr = srv.recvfrom(1024)
1174
1175 self.assertEqual(cli.getsockname(), recvaddr)
1176 self.assertEqual(msg, MSG)
1177
1178
1179class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1180 def __init__(self, methodName = 'runTest'):
1181 unittest.TestCase.__init__(self, methodName = methodName)
1182 ThreadableTest.__init__(self)
1183
1184 def setUp(self):
1185 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1186 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1187 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1188 TIPC_LOWER, TIPC_UPPER)
1189 self.srv.bind(srvaddr)
1190 self.srv.listen(5)
1191 self.serverExplicitReady()
1192 self.conn, self.connaddr = self.srv.accept()
1193
1194 def clientSetUp(self):
1195 # The is a hittable race between serverExplicitReady() and the
1196 # accept() call; sleep a little while to avoid it, otherwise
1197 # we could get an exception
1198 time.sleep(0.1)
1199 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1200 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1201 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1202 self.cli.connect(addr)
1203 self.cliaddr = self.cli.getsockname()
1204
1205 def testStream(self):
1206 msg = self.conn.recv(1024)
1207 self.assertEqual(msg, MSG)
1208 self.assertEqual(self.cliaddr, self.connaddr)
1209
1210 def _testStream(self):
1211 self.cli.send(MSG)
1212 self.cli.close()
1213
1214
Guido van Rossumb995eb72002-07-31 16:08:40 +00001215def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001216 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001218 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001219 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001220
1221 tests.extend([
1222 NonBlockingTCPTests,
1223 FileObjectClassTestCase,
1224 UnbufferedFileObjectClassTestCase,
1225 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001226 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001227 NetworkConnectionNoServer,
1228 NetworkConnectionAttributesTest,
1229 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001230 ])
Dave Cole331708b2004-08-09 04:51:41 +00001231 if hasattr(socket, "socketpair"):
1232 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001233 if sys.platform == 'linux2':
1234 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001235 if isTipcAvailable():
1236 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001237 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001238
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001239 thread_info = support.threading_setup()
1240 support.run_unittest(*tests)
1241 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001242
1243if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001244 test_main()