blob: 2bec373ed965debece65b4d556d86f0fb97ae0b5 [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
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test import test_support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Barry Warsawcf3d4b51997-01-03 20:03:32 +00006import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00007import select
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import thread, threading
Christian Heimesbbe741d2008-03-28 10:53:29 +00009import time
10import traceback
Guido van Rossum24e4af82002-06-12 19:18:08 +000011import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000012import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000013import os
14import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000015from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000016import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000017
Guido van Rossum24e4af82002-06-12 19:18:08 +000018PORT = 50007
19HOST = 'localhost'
Guido van Rossum7d0a8262007-05-21 23:13:11 +000020MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Guido van Rossum24e4af82002-06-12 19:18:08 +000022class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000023
Guido van Rossum24e4af82002-06-12 19:18:08 +000024 def setUp(self):
25 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000027 global PORT
28 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000029 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000030
Guido van Rossum24e4af82002-06-12 19:18:08 +000031 def tearDown(self):
32 self.serv.close()
33 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000034
Guido van Rossum24e4af82002-06-12 19:18:08 +000035class SocketUDPTest(unittest.TestCase):
36
37 def setUp(self):
38 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
39 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 global PORT
41 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000042
43 def tearDown(self):
44 self.serv.close()
45 self.serv = None
46
47class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000048 """Threadable Test class
49
50 The ThreadableTest class makes it easy to create a threaded
51 client/server pair from an existing unit test. To create a
52 new threaded class from an existing unit test, use multiple
53 inheritance:
54
55 class NewClass (OldClass, ThreadableTest):
56 pass
57
58 This class defines two new fixture functions with obvious
59 purposes for overriding:
60
61 clientSetUp ()
62 clientTearDown ()
63
64 Any new test functions within the class must then define
65 tests in pairs, where the test name is preceeded with a
66 '_' to indicate the client portion of the test. Ex:
67
68 def testFoo(self):
69 # Server portion
70
71 def _testFoo(self):
72 # Client portion
73
74 Any exceptions raised by the clients during their tests
75 are caught and transferred to the main thread to alert
76 the testing framework.
77
78 Note, the server setup function cannot call any blocking
79 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000080 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000081 the blocking call (such as in setting up a client/server
82 connection and performing the accept() in setUp().
83 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000084
85 def __init__(self):
86 # Swap the true setup function
87 self.__setUp = self.setUp
88 self.__tearDown = self.tearDown
89 self.setUp = self._setUp
90 self.tearDown = self._tearDown
91
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000092 def serverExplicitReady(self):
93 """This method allows the server to explicitly indicate that
94 it wants the client thread to proceed. This is useful if the
95 server is about to execute a blocking routine that is
96 dependent upon the client thread during its setup routine."""
97 self.server_ready.set()
98
Guido van Rossum24e4af82002-06-12 19:18:08 +000099 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000100 self.server_ready = threading.Event()
101 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000102 self.done = threading.Event()
103 self.queue = Queue.Queue(1)
104
105 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000106 methodname = self.id()
107 i = methodname.rfind('.')
108 methodname = methodname[i+1:]
109 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000110 self.client_thread = thread.start_new_thread(
111 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000112
113 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000114 if not self.server_ready.isSet():
115 self.server_ready.set()
116 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000117
118 def _tearDown(self):
119 self.__tearDown()
120 self.done.wait()
121
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000122 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000123 msg = self.queue.get()
124 self.fail(msg)
125
126 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000127 self.server_ready.wait()
128 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000130 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000131 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000132 try:
133 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000134 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000135 self.queue.put(strerror)
136 self.clientTearDown()
137
138 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000139 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000140
141 def clientTearDown(self):
142 self.done.set()
143 thread.exit()
144
145class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
146
147 def __init__(self, methodName='runTest'):
148 SocketTCPTest.__init__(self, methodName=methodName)
149 ThreadableTest.__init__(self)
150
151 def clientSetUp(self):
152 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
153
154 def clientTearDown(self):
155 self.cli.close()
156 self.cli = None
157 ThreadableTest.clientTearDown(self)
158
159class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
160
161 def __init__(self, methodName='runTest'):
162 SocketUDPTest.__init__(self, methodName=methodName)
163 ThreadableTest.__init__(self)
164
165 def clientSetUp(self):
166 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
167
168class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000169 """Socket tests for client-server connection.
170
171 self.cli_conn is a client socket connected to the server. The
172 setUp() method guarantees that it is connected to the server.
173 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000174
175 def __init__(self, methodName='runTest'):
176 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
177
178 def setUp(self):
179 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000180 # Indicate explicitly we're ready for the client thread to
181 # proceed and then perform the blocking call to accept
182 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000183 conn, addr = self.serv.accept()
184 self.cli_conn = conn
185
186 def tearDown(self):
187 self.cli_conn.close()
188 self.cli_conn = None
189 ThreadedTCPSocketTest.tearDown(self)
190
191 def clientSetUp(self):
192 ThreadedTCPSocketTest.clientSetUp(self)
193 self.cli.connect((HOST, PORT))
194 self.serv_conn = self.cli
195
196 def clientTearDown(self):
197 self.serv_conn.close()
198 self.serv_conn = None
199 ThreadedTCPSocketTest.clientTearDown(self)
200
Dave Cole331708b2004-08-09 04:51:41 +0000201class SocketPairTest(unittest.TestCase, ThreadableTest):
202
203 def __init__(self, methodName='runTest'):
204 unittest.TestCase.__init__(self, methodName=methodName)
205 ThreadableTest.__init__(self)
206
207 def setUp(self):
208 self.serv, self.cli = socket.socketpair()
209
210 def tearDown(self):
211 self.serv.close()
212 self.serv = None
213
214 def clientSetUp(self):
215 pass
216
217 def clientTearDown(self):
218 self.cli.close()
219 self.cli = None
220 ThreadableTest.clientTearDown(self)
221
Tim Peters494aaee2004-08-09 18:54:11 +0000222
Guido van Rossum24e4af82002-06-12 19:18:08 +0000223#######################################################################
224## Begin Tests
225
226class GeneralModuleTests(unittest.TestCase):
227
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000228 def test_repr(self):
229 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
230 self.assert_(repr(s).startswith("<socket.socket object"))
231
Raymond Hettinger027bb632004-05-31 03:09:25 +0000232 def test_weakref(self):
233 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
234 p = proxy(s)
235 self.assertEqual(p.fileno(), s.fileno())
236 s.close()
237 s = None
238 try:
239 p.fileno()
240 except ReferenceError:
241 pass
242 else:
243 self.fail('Socket proxy still exists')
244
Guido van Rossum24e4af82002-06-12 19:18:08 +0000245 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000246 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000247 def raise_error(*args, **kwargs):
248 raise socket.error
249 def raise_herror(*args, **kwargs):
250 raise socket.herror
251 def raise_gaierror(*args, **kwargs):
252 raise socket.gaierror
253 self.failUnlessRaises(socket.error, raise_error,
254 "Error raising socket exception.")
255 self.failUnlessRaises(socket.error, raise_herror,
256 "Error raising socket exception.")
257 self.failUnlessRaises(socket.error, raise_gaierror,
258 "Error raising socket exception.")
259
260 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000261 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000262 socket.AF_INET
263 socket.SOCK_STREAM
264 socket.SOCK_DGRAM
265 socket.SOCK_RAW
266 socket.SOCK_RDM
267 socket.SOCK_SEQPACKET
268 socket.SOL_SOCKET
269 socket.SO_REUSEADDR
270
Guido van Rossum654c11e2002-06-13 20:24:17 +0000271 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000272 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000273 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000274 try:
275 ip = socket.gethostbyname(hostname)
276 except socket.error:
277 # Probably name lookup wasn't set up right; skip this test
278 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000279 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000280 try:
281 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
282 except socket.error:
283 # Probably a similar problem as above; skip this test
284 return
Brett Cannon01668a12005-03-11 00:04:17 +0000285 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000287 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000289
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000290 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000291 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000292 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000293 try:
294 # On some versions, this loses a reference
295 orig = sys.getrefcount(__name__)
296 socket.getnameinfo(__name__,0)
297 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000298 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000299 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000300
Guido van Rossum24e4af82002-06-12 19:18:08 +0000301 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000302 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000303 try:
304 # On some versions, this crashes the interpreter.
305 socket.getnameinfo(('x', 0, 0, 0), 0)
306 except socket.error:
307 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000308
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000309 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000310 # This just checks that htons etc. are their own inverse,
311 # when looking at the lower 16 or 32 bits.
312 sizes = {socket.htonl: 32, socket.ntohl: 32,
313 socket.htons: 16, socket.ntohs: 16}
314 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000315 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000316 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
317 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000318
Guido van Rossuma2627af2002-09-14 00:58:46 +0000319 swapped = func(mask)
320 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000321 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000322
Guido van Rossum018919a2007-01-15 00:07:32 +0000323 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000324 good_values = [ 1, 2, 3, 1, 2, 3 ]
325 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000326 for k in good_values:
327 socket.ntohl(k)
328 socket.ntohs(k)
329 socket.htonl(k)
330 socket.htons(k)
331 for k in bad_values:
332 self.assertRaises(OverflowError, socket.ntohl, k)
333 self.assertRaises(OverflowError, socket.ntohs, k)
334 self.assertRaises(OverflowError, socket.htonl, k)
335 self.assertRaises(OverflowError, socket.htons, k)
336
Barry Warsaw11b91a02004-06-28 00:50:43 +0000337 def testGetServBy(self):
338 eq = self.assertEqual
339 # Find one service that exists, then check all the related interfaces.
340 # I've ordered this by protocols that have both a tcp and udp
341 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000342 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000343 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000344 # avoid the 'echo' service on this platform, as there is an
345 # assumption breaking non-standard port/protocol entry
346 services = ('daytime', 'qotd', 'domain')
347 else:
348 services = ('echo', 'daytime', 'domain')
349 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000350 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000351 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000352 break
353 except socket.error:
354 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000355 else:
356 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000357 # Try same call with optional protocol omitted
358 port2 = socket.getservbyname(service)
359 eq(port, port2)
360 # Try udp, but don't barf it it doesn't exist
361 try:
362 udpport = socket.getservbyname(service, 'udp')
363 except socket.error:
364 udpport = None
365 else:
366 eq(udpport, port)
367 # Now make sure the lookup by port returns the same service name
368 eq(socket.getservbyport(port2), service)
369 eq(socket.getservbyport(port, 'tcp'), service)
370 if udpport is not None:
371 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000372
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000373 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000374 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000375 # The default timeout should initially be None
376 self.assertEqual(socket.getdefaulttimeout(), None)
377 s = socket.socket()
378 self.assertEqual(s.gettimeout(), None)
379 s.close()
380
381 # Set the default timeout to 10, and see if it propagates
382 socket.setdefaulttimeout(10)
383 self.assertEqual(socket.getdefaulttimeout(), 10)
384 s = socket.socket()
385 self.assertEqual(s.gettimeout(), 10)
386 s.close()
387
388 # Reset the default timeout to None, and see if it propagates
389 socket.setdefaulttimeout(None)
390 self.assertEqual(socket.getdefaulttimeout(), None)
391 s = socket.socket()
392 self.assertEqual(s.gettimeout(), None)
393 s.close()
394
395 # Check that setting it to an invalid value raises ValueError
396 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
397
398 # Check that setting it to an invalid type raises TypeError
399 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
400
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000401 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000402 if not hasattr(socket, 'inet_pton'):
403 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000404 from socket import inet_aton as f, inet_pton, AF_INET
405 g = lambda a: inet_pton(AF_INET, a)
406
Guido van Rossumb5b22702007-05-18 18:55:53 +0000407 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
408 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
409 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
410 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
411 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000412
Guido van Rossumb5b22702007-05-18 18:55:53 +0000413 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
414 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
415 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
416 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000417
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000418 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000419 if not hasattr(socket, 'inet_pton'):
420 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000421 try:
422 from socket import inet_pton, AF_INET6, has_ipv6
423 if not has_ipv6:
424 return
425 except ImportError:
426 return
427 f = lambda a: inet_pton(AF_INET6, a)
428
Guido van Rossum540d9872007-08-17 03:51:09 +0000429 self.assertEquals(b'\x00' * 16, f('::'))
430 self.assertEquals(b'\x00' * 16, f('0::0'))
431 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000432 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000433 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 +0000434 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
435 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000436
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000437 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000438 if not hasattr(socket, 'inet_ntop'):
439 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000440 from socket import inet_ntoa as f, inet_ntop, AF_INET
441 g = lambda a: inet_ntop(AF_INET, a)
442
Guido van Rossumb5b22702007-05-18 18:55:53 +0000443 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
444 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
445 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
446 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000447
Guido van Rossumb5b22702007-05-18 18:55:53 +0000448 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
449 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
450 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000451
452 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000453 if not hasattr(socket, 'inet_ntop'):
454 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000455 try:
456 from socket import inet_ntop, AF_INET6, has_ipv6
457 if not has_ipv6:
458 return
459 except ImportError:
460 return
461 f = lambda a: inet_ntop(AF_INET6, a)
462
Guido van Rossum540d9872007-08-17 03:51:09 +0000463 self.assertEquals('::', f(b'\x00' * 16))
464 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000465 self.assertEquals(
466 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000467 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 +0000468 )
469
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000470 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000471
Guido van Rossum24e4af82002-06-12 19:18:08 +0000472 def testSockName(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000473 # Testing getsockname()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000474 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000475 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000476 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
478 # it reasonable to get the host's addr in addition to 0.0.0.0.
479 # At least for eCos. This is required for the S/390 to pass.
480 my_ip_addr = socket.gethostbyname(socket.gethostname())
481 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
482 self.assertEqual(name[1], PORT+1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000483
484 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000485 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000486 # We know a socket should start without reuse==0
487 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
488 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000489 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000490
491 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000492 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000493 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
494 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
495 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000496 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000497
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000498 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000499 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000500 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
501 sock.settimeout(1)
502 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000503 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000504
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505 def testNewAttributes(self):
506 # testing .family, .type and .protocol
507 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
508 self.assertEqual(sock.family, socket.AF_INET)
509 self.assertEqual(sock.type, socket.SOCK_STREAM)
510 self.assertEqual(sock.proto, 0)
511 sock.close()
512
Christian Heimesfaf2f632008-01-06 16:59:19 +0000513 def test_sock_ioctl(self):
514 if os.name != "nt":
515 return
516 self.assert_(hasattr(socket.socket, 'ioctl'))
517 self.assert_(hasattr(socket, 'SIO_RCVALL'))
518 self.assert_(hasattr(socket, 'RCVALL_ON'))
519 self.assert_(hasattr(socket, 'RCVALL_OFF'))
520
521
Guido van Rossum24e4af82002-06-12 19:18:08 +0000522class BasicTCPTest(SocketConnectedTest):
523
524 def __init__(self, methodName='runTest'):
525 SocketConnectedTest.__init__(self, methodName=methodName)
526
527 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000528 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000529 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000530 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000531
532 def _testRecv(self):
533 self.serv_conn.send(MSG)
534
535 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000536 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000537 seg1 = self.cli_conn.recv(len(MSG) - 3)
538 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000539 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000540 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000541
542 def _testOverFlowRecv(self):
543 self.serv_conn.send(MSG)
544
545 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000546 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000547 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000548 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000549
550 def _testRecvFrom(self):
551 self.serv_conn.send(MSG)
552
553 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000554 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000555 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
556 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000557 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000558 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000559
560 def _testOverFlowRecvFrom(self):
561 self.serv_conn.send(MSG)
562
563 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000564 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000565 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000566 while 1:
567 read = self.cli_conn.recv(1024)
568 if not read:
569 break
Guido van Rossume531e292002-08-08 20:28:34 +0000570 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000571 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000572
573 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000574 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000575 self.serv_conn.sendall(big_chunk)
576
577 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000578 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000579 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000580 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000581 fd = self.cli_conn.fileno()
582 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
583 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000584 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000585
586 def _testFromFd(self):
587 self.serv_conn.send(MSG)
588
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000589 def testDup(self):
590 # Testing dup()
591 sock = self.cli_conn.dup()
592 msg = sock.recv(1024)
593 self.assertEqual(msg, MSG)
594
595 def _testDup(self):
596 self.serv_conn.send(MSG)
597
Guido van Rossum24e4af82002-06-12 19:18:08 +0000598 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000599 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000600 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000601 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000602
603 def _testShutdown(self):
604 self.serv_conn.send(MSG)
605 self.serv_conn.shutdown(2)
606
607class BasicUDPTest(ThreadedUDPSocketTest):
608
609 def __init__(self, methodName='runTest'):
610 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
611
612 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000613 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000614 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000615 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000616
617 def _testSendtoAndRecv(self):
618 self.cli.sendto(MSG, 0, (HOST, PORT))
619
Guido van Rossum1c938012002-06-12 21:17:20 +0000620 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000621 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000622 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000623 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000624
Guido van Rossum1c938012002-06-12 21:17:20 +0000625 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000626 self.cli.sendto(MSG, 0, (HOST, PORT))
627
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 def testRecvFromNegative(self):
629 # Negative lengths passed to recvfrom should give ValueError.
630 self.assertRaises(ValueError, self.serv.recvfrom, -1)
631
632 def _testRecvFromNegative(self):
633 self.cli.sendto(MSG, 0, (HOST, PORT))
634
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000635class TCPCloserTest(ThreadedTCPSocketTest):
636
637 def testClose(self):
638 conn, addr = self.serv.accept()
639 conn.close()
640
641 sd = self.cli
642 read, write, err = select.select([sd], [], [], 1.0)
643 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000644 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000646 # Calling close() many times should be safe.
647 conn.close()
648 conn.close()
649
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650 def _testClose(self):
651 self.cli.connect((HOST, PORT))
652 time.sleep(1.0)
653
Dave Cole331708b2004-08-09 04:51:41 +0000654class BasicSocketPairTest(SocketPairTest):
655
656 def __init__(self, methodName='runTest'):
657 SocketPairTest.__init__(self, methodName=methodName)
658
659 def testRecv(self):
660 msg = self.serv.recv(1024)
661 self.assertEqual(msg, MSG)
662
663 def _testRecv(self):
664 self.cli.send(MSG)
665
666 def testSend(self):
667 self.serv.send(MSG)
668
669 def _testSend(self):
670 msg = self.cli.recv(1024)
671 self.assertEqual(msg, MSG)
672
Guido van Rossum24e4af82002-06-12 19:18:08 +0000673class NonBlockingTCPTests(ThreadedTCPSocketTest):
674
675 def __init__(self, methodName='runTest'):
676 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
677
678 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000679 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000680 self.serv.setblocking(0)
681 start = time.time()
682 try:
683 self.serv.accept()
684 except socket.error:
685 pass
686 end = time.time()
687 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
688
689 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000690 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000691
Guido van Rossum24e4af82002-06-12 19:18:08 +0000692 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000693 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000694 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000695 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000696 conn, addr = self.serv.accept()
697 except socket.error:
698 pass
699 else:
700 self.fail("Error trying to do non-blocking accept.")
701 read, write, err = select.select([self.serv], [], [])
702 if self.serv in read:
703 conn, addr = self.serv.accept()
704 else:
705 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000706
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000708 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000709 self.cli.connect((HOST, PORT))
710
711 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000712 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713 conn, addr = self.serv.accept()
714
715 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000716 self.cli.settimeout(10)
717 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000718
719 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000720 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721 conn, addr = self.serv.accept()
722 conn.setblocking(0)
723 try:
724 msg = conn.recv(len(MSG))
725 except socket.error:
726 pass
727 else:
728 self.fail("Error trying to do non-blocking recv.")
729 read, write, err = select.select([conn], [], [])
730 if conn in read:
731 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000732 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000733 else:
734 self.fail("Error during select call to non-blocking socket.")
735
736 def _testRecv(self):
737 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000738 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000739 self.cli.send(MSG)
740
741class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000742 """Unit tests for the object returned by socket.makefile()
743
744 self.serv_file is the io object returned by makefile() on
745 the client connection. You can read from this file to
746 get output from the server.
747
748 self.cli_file is the io object returned by makefile() on the
749 server connection. You can write to this file to send output
750 to the client.
751 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000752
Guido van Rossume9f66142002-08-07 15:46:19 +0000753 bufsize = -1 # Use default buffer size
754
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755 def __init__(self, methodName='runTest'):
756 SocketConnectedTest.__init__(self, methodName=methodName)
757
758 def setUp(self):
759 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000760 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000761
762 def tearDown(self):
763 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000764 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000765 self.serv_file = None
766 SocketConnectedTest.tearDown(self)
767
768 def clientSetUp(self):
769 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000770 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000771
772 def clientTearDown(self):
773 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000774 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000775 self.cli_file = None
776 SocketConnectedTest.clientTearDown(self)
777
778 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000779 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000780 first_seg = self.serv_file.read(len(MSG)-3)
781 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000782 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000783 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000784
785 def _testSmallRead(self):
786 self.cli_file.write(MSG)
787 self.cli_file.flush()
788
Guido van Rossum8c943832002-08-08 01:00:28 +0000789 def testFullRead(self):
790 # read until EOF
791 msg = self.serv_file.read()
792 self.assertEqual(msg, MSG)
793
794 def _testFullRead(self):
795 self.cli_file.write(MSG)
796 self.cli_file.close()
797
Guido van Rossum24e4af82002-06-12 19:18:08 +0000798 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000799 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000800 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000801 while 1:
802 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000803 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000804 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000805 buf += char
806 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000807
808 def _testUnbufferedRead(self):
809 self.cli_file.write(MSG)
810 self.cli_file.flush()
811
812 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000813 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000814 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000815 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000816
817 def _testReadline(self):
818 self.cli_file.write(MSG)
819 self.cli_file.flush()
820
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000821 def testCloseAfterMakefile(self):
822 # The file returned by makefile should keep the socket open.
823 self.cli_conn.close()
824 # read until EOF
825 msg = self.serv_file.read()
826 self.assertEqual(msg, MSG)
827
828 def _testCloseAfterMakefile(self):
829 self.cli_file.write(MSG)
830 self.cli_file.flush()
831
832 def testMakefileAfterMakefileClose(self):
833 self.serv_file.close()
834 msg = self.cli_conn.recv(len(MSG))
835 self.assertEqual(msg, MSG)
836
837 def _testMakefileAfterMakefileClose(self):
838 self.cli_file.write(MSG)
839 self.cli_file.flush()
840
Tim Peters116d83c2004-03-28 02:20:45 +0000841 def testClosedAttr(self):
842 self.assert_(not self.serv_file.closed)
843
844 def _testClosedAttr(self):
845 self.assert_(not self.cli_file.closed)
846
Guido van Rossume9f66142002-08-07 15:46:19 +0000847class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
848
849 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000850
Guido van Rossume9f66142002-08-07 15:46:19 +0000851 In this case (and in this case only), it should be possible to
852 create a file object, read a line from it, create another file
853 object, read another line from it, without loss of data in the
854 first file object's buffer. Note that httplib relies on this
855 when reading multiple requests from the same socket."""
856
857 bufsize = 0 # Use unbuffered mode
858
859 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000860 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000861 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000862 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000863 self.serv_file = self.cli_conn.makefile('rb', 0)
864 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000865 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000866
867 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000868 self.cli_file.write(b"A. " + MSG)
869 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000870 self.cli_file.flush()
871
Guido van Rossum8c943832002-08-08 01:00:28 +0000872class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
873
874 bufsize = 1 # Default-buffered for reading; line-buffered for writing
875
876
877class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
878
879 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000880
Thomas Woutersb2137042007-02-01 18:02:27 +0000881
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882class NetworkConnectionTest(object):
883 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000884
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885 def clientSetUp(self):
886 self.cli = socket.create_connection((HOST, PORT))
887 self.serv_conn = self.cli
888
889class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
890 """Tests that NetworkConnection does not break existing TCP functionality.
891 """
892
893class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000894
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895 def testWithoutServer(self):
896 self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
897
898class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
899
900 def __init__(self, methodName='runTest'):
901 SocketTCPTest.__init__(self, methodName=methodName)
902 ThreadableTest.__init__(self)
903
904 def clientSetUp(self):
905 pass
906
907 def clientTearDown(self):
908 self.cli.close()
909 self.cli = None
910 ThreadableTest.clientTearDown(self)
911
912 def _justAccept(self):
913 conn, addr = self.serv.accept()
914
915 testFamily = _justAccept
916 def _testFamily(self):
917 self.cli = socket.create_connection((HOST, PORT), timeout=30)
918 self.assertEqual(self.cli.family, 2)
919
920 testTimeoutDefault = _justAccept
921 def _testTimeoutDefault(self):
922 self.cli = socket.create_connection((HOST, PORT))
923 self.assertTrue(self.cli.gettimeout() is None)
924
925 testTimeoutValueNamed = _justAccept
926 def _testTimeoutValueNamed(self):
927 self.cli = socket.create_connection((HOST, PORT), timeout=30)
928 self.assertEqual(self.cli.gettimeout(), 30)
929
930 testTimeoutValueNonamed = _justAccept
931 def _testTimeoutValueNonamed(self):
932 self.cli = socket.create_connection((HOST, PORT), 30)
933 self.assertEqual(self.cli.gettimeout(), 30)
934
935 testTimeoutNone = _justAccept
936 def _testTimeoutNone(self):
937 previous = socket.getdefaulttimeout()
938 socket.setdefaulttimeout(30)
939 try:
940 self.cli = socket.create_connection((HOST, PORT), timeout=None)
941 finally:
942 socket.setdefaulttimeout(previous)
943 self.assertEqual(self.cli.gettimeout(), 30)
944
945
946class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
947
948 def __init__(self, methodName='runTest'):
949 SocketTCPTest.__init__(self, methodName=methodName)
950 ThreadableTest.__init__(self)
951
952 def clientSetUp(self):
953 pass
954
955 def clientTearDown(self):
956 self.cli.close()
957 self.cli = None
958 ThreadableTest.clientTearDown(self)
959
960 def testInsideTimeout(self):
961 conn, addr = self.serv.accept()
962 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000963 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964 testOutsideTimeout = testInsideTimeout
965
966 def _testInsideTimeout(self):
967 self.cli = sock = socket.create_connection((HOST, PORT))
968 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000969 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970
971 def _testOutsideTimeout(self):
972 self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
973 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
974
975
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000976class TCPTimeoutTest(SocketTCPTest):
977
978 def testTCPTimeout(self):
979 def raise_timeout(*args, **kwargs):
980 self.serv.settimeout(1.0)
981 self.serv.accept()
982 self.failUnlessRaises(socket.timeout, raise_timeout,
983 "Error generating a timeout exception (TCP)")
984
985 def testTimeoutZero(self):
986 ok = False
987 try:
988 self.serv.settimeout(0.0)
989 foo = self.serv.accept()
990 except socket.timeout:
991 self.fail("caught timeout instead of error (TCP)")
992 except socket.error:
993 ok = True
994 except:
995 self.fail("caught unexpected exception (TCP)")
996 if not ok:
997 self.fail("accept() returned success when we did not expect it")
998
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000999 def testInterruptedTimeout(self):
1000 # XXX I don't know how to do this test on MSWindows or any other
1001 # plaform that doesn't support signal.alarm() or os.kill(), though
1002 # the bug should have existed on all platforms.
1003 if not hasattr(signal, "alarm"):
1004 return # can only test on *nix
1005 self.serv.settimeout(5.0) # must be longer than alarm
1006 class Alarm(Exception):
1007 pass
1008 def alarm_handler(signal, frame):
1009 raise Alarm
1010 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1011 try:
1012 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1013 try:
1014 foo = self.serv.accept()
1015 except socket.timeout:
1016 self.fail("caught timeout instead of Alarm")
1017 except Alarm:
1018 pass
1019 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001020 self.fail("caught other exception instead of Alarm:"
1021 " %s(%s):\n%s" %
1022 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001023 else:
1024 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001025 finally:
1026 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 except Alarm:
1028 self.fail("got Alarm in wrong place")
1029 finally:
1030 # no alarm can be pending. Safe to restore old handler.
1031 signal.signal(signal.SIGALRM, old_alarm)
1032
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001033class UDPTimeoutTest(SocketTCPTest):
1034
1035 def testUDPTimeout(self):
1036 def raise_timeout(*args, **kwargs):
1037 self.serv.settimeout(1.0)
1038 self.serv.recv(1024)
1039 self.failUnlessRaises(socket.timeout, raise_timeout,
1040 "Error generating a timeout exception (UDP)")
1041
1042 def testTimeoutZero(self):
1043 ok = False
1044 try:
1045 self.serv.settimeout(0.0)
1046 foo = self.serv.recv(1024)
1047 except socket.timeout:
1048 self.fail("caught timeout instead of error (UDP)")
1049 except socket.error:
1050 ok = True
1051 except:
1052 self.fail("caught unexpected exception (UDP)")
1053 if not ok:
1054 self.fail("recv() returned success when we did not expect it")
1055
1056class TestExceptions(unittest.TestCase):
1057
1058 def testExceptionTree(self):
1059 self.assert_(issubclass(socket.error, Exception))
1060 self.assert_(issubclass(socket.herror, socket.error))
1061 self.assert_(issubclass(socket.gaierror, socket.error))
1062 self.assert_(issubclass(socket.timeout, socket.error))
1063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001064class TestLinuxAbstractNamespace(unittest.TestCase):
1065
1066 UNIX_PATH_MAX = 108
1067
1068 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001069 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001070 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1071 s1.bind(address)
1072 s1.listen(1)
1073 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1074 s2.connect(s1.getsockname())
1075 s1.accept()
1076 self.assertEqual(s1.getsockname(), address)
1077 self.assertEqual(s2.getpeername(), address)
1078
1079 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001080 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001081 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1082 s.bind(address)
1083 self.assertEqual(s.getsockname(), address)
1084
1085 def testNameOverflow(self):
1086 address = "\x00" + "h" * self.UNIX_PATH_MAX
1087 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1088 self.assertRaises(socket.error, s.bind, address)
1089
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001090
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091class BufferIOTest(SocketConnectedTest):
1092 """
1093 Test the buffer versions of socket.recv() and socket.send().
1094 """
1095 def __init__(self, methodName='runTest'):
1096 SocketConnectedTest.__init__(self, methodName=methodName)
1097
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001098 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001099 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001100 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001102 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103 self.assertEqual(msg, MSG)
1104
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001105 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001106 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107 self.serv_conn.send(buf)
1108
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001109 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001110 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001111 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001113 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 self.assertEqual(msg, MSG)
1115
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001116 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001117 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118 self.serv_conn.send(buf)
1119
Christian Heimes043d6f62008-01-07 17:19:16 +00001120
1121TIPC_STYPE = 2000
1122TIPC_LOWER = 200
1123TIPC_UPPER = 210
1124
1125def isTipcAvailable():
1126 """Check if the TIPC module is loaded
1127
1128 The TIPC module is not loaded automatically on Ubuntu and probably
1129 other Linux distros.
1130 """
1131 if not hasattr(socket, "AF_TIPC"):
1132 return False
1133 if not os.path.isfile("/proc/modules"):
1134 return False
1135 with open("/proc/modules") as f:
1136 for line in f:
1137 if line.startswith("tipc "):
1138 return True
Christian Heimes2380ac72008-01-09 00:17:24 +00001139 if test_support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001140 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1141 return False
1142
1143class TIPCTest (unittest.TestCase):
1144 def testRDM(self):
1145 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1146 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1147
1148 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1149 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1150 TIPC_LOWER, TIPC_UPPER)
1151 srv.bind(srvaddr)
1152
1153 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1154 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1155 cli.sendto(MSG, sendaddr)
1156
1157 msg, recvaddr = srv.recvfrom(1024)
1158
1159 self.assertEqual(cli.getsockname(), recvaddr)
1160 self.assertEqual(msg, MSG)
1161
1162
1163class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1164 def __init__(self, methodName = 'runTest'):
1165 unittest.TestCase.__init__(self, methodName = methodName)
1166 ThreadableTest.__init__(self)
1167
1168 def setUp(self):
1169 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1170 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1171 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1172 TIPC_LOWER, TIPC_UPPER)
1173 self.srv.bind(srvaddr)
1174 self.srv.listen(5)
1175 self.serverExplicitReady()
1176 self.conn, self.connaddr = self.srv.accept()
1177
1178 def clientSetUp(self):
1179 # The is a hittable race between serverExplicitReady() and the
1180 # accept() call; sleep a little while to avoid it, otherwise
1181 # we could get an exception
1182 time.sleep(0.1)
1183 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1184 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1185 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1186 self.cli.connect(addr)
1187 self.cliaddr = self.cli.getsockname()
1188
1189 def testStream(self):
1190 msg = self.conn.recv(1024)
1191 self.assertEqual(msg, MSG)
1192 self.assertEqual(self.cliaddr, self.connaddr)
1193
1194 def _testStream(self):
1195 self.cli.send(MSG)
1196 self.cli.close()
1197
1198
Guido van Rossumb995eb72002-07-31 16:08:40 +00001199def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001200 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001201 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001202 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001203 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001204
1205 tests.extend([
1206 NonBlockingTCPTests,
1207 FileObjectClassTestCase,
1208 UnbufferedFileObjectClassTestCase,
1209 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001210 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 NetworkConnectionNoServer,
1212 NetworkConnectionAttributesTest,
1213 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001214 ])
Dave Cole331708b2004-08-09 04:51:41 +00001215 if hasattr(socket, "socketpair"):
1216 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 if sys.platform == 'linux2':
1218 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001219 if isTipcAvailable():
1220 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001221 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222
1223 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001224 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001225 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001226
1227if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001228 test_main()