blob: d3b870f9b8d718b106071d6ed4474d3895cdef0d [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
Barry Warsawcf3d4b51997-01-03 20:03:32 +00008import time
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import thread, threading
10import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000011import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000012import os
13import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000014from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000016
Guido van Rossum24e4af82002-06-12 19:18:08 +000017PORT = 50007
18HOST = 'localhost'
Guido van Rossum7d0a8262007-05-21 23:13:11 +000019MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000020
Guido van Rossum24e4af82002-06-12 19:18:08 +000021class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000022
Guido van Rossum24e4af82002-06-12 19:18:08 +000023 def setUp(self):
24 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026 global PORT
27 PORT = test_support.bind_port(self.serv, HOST, PORT)
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)
38 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039 global PORT
40 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000041
42 def tearDown(self):
43 self.serv.close()
44 self.serv = None
45
46class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000047 """Threadable Test class
48
49 The ThreadableTest class makes it easy to create a threaded
50 client/server pair from an existing unit test. To create a
51 new threaded class from an existing unit test, use multiple
52 inheritance:
53
54 class NewClass (OldClass, ThreadableTest):
55 pass
56
57 This class defines two new fixture functions with obvious
58 purposes for overriding:
59
60 clientSetUp ()
61 clientTearDown ()
62
63 Any new test functions within the class must then define
64 tests in pairs, where the test name is preceeded with a
65 '_' to indicate the client portion of the test. Ex:
66
67 def testFoo(self):
68 # Server portion
69
70 def _testFoo(self):
71 # Client portion
72
73 Any exceptions raised by the clients during their tests
74 are caught and transferred to the main thread to alert
75 the testing framework.
76
77 Note, the server setup function cannot call any blocking
78 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000079 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000080 the blocking call (such as in setting up a client/server
81 connection and performing the accept() in setUp().
82 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000083
84 def __init__(self):
85 # Swap the true setup function
86 self.__setUp = self.setUp
87 self.__tearDown = self.tearDown
88 self.setUp = self._setUp
89 self.tearDown = self._tearDown
90
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000091 def serverExplicitReady(self):
92 """This method allows the server to explicitly indicate that
93 it wants the client thread to proceed. This is useful if the
94 server is about to execute a blocking routine that is
95 dependent upon the client thread during its setup routine."""
96 self.server_ready.set()
97
Guido van Rossum24e4af82002-06-12 19:18:08 +000098 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000099 self.server_ready = threading.Event()
100 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000101 self.done = threading.Event()
102 self.queue = Queue.Queue(1)
103
104 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000105 methodname = self.id()
106 i = methodname.rfind('.')
107 methodname = methodname[i+1:]
108 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000109 self.client_thread = thread.start_new_thread(
110 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000111
112 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000113 if not self.server_ready.isSet():
114 self.server_ready.set()
115 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116
117 def _tearDown(self):
118 self.__tearDown()
119 self.done.wait()
120
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000121 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000122 msg = self.queue.get()
123 self.fail(msg)
124
125 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000126 self.server_ready.wait()
127 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000128 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000129 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000130 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000131 try:
132 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000133 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000134 self.queue.put(strerror)
135 self.clientTearDown()
136
137 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000138 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000139
140 def clientTearDown(self):
141 self.done.set()
142 thread.exit()
143
144class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
145
146 def __init__(self, methodName='runTest'):
147 SocketTCPTest.__init__(self, methodName=methodName)
148 ThreadableTest.__init__(self)
149
150 def clientSetUp(self):
151 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
152
153 def clientTearDown(self):
154 self.cli.close()
155 self.cli = None
156 ThreadableTest.clientTearDown(self)
157
158class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
159
160 def __init__(self, methodName='runTest'):
161 SocketUDPTest.__init__(self, methodName=methodName)
162 ThreadableTest.__init__(self)
163
164 def clientSetUp(self):
165 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
166
167class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000168 """Socket tests for client-server connection.
169
170 self.cli_conn is a client socket connected to the server. The
171 setUp() method guarantees that it is connected to the server.
172 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000173
174 def __init__(self, methodName='runTest'):
175 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
176
177 def setUp(self):
178 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000179 # Indicate explicitly we're ready for the client thread to
180 # proceed and then perform the blocking call to accept
181 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000182 conn, addr = self.serv.accept()
183 self.cli_conn = conn
184
185 def tearDown(self):
186 self.cli_conn.close()
187 self.cli_conn = None
188 ThreadedTCPSocketTest.tearDown(self)
189
190 def clientSetUp(self):
191 ThreadedTCPSocketTest.clientSetUp(self)
192 self.cli.connect((HOST, PORT))
193 self.serv_conn = self.cli
194
195 def clientTearDown(self):
196 self.serv_conn.close()
197 self.serv_conn = None
198 ThreadedTCPSocketTest.clientTearDown(self)
199
Dave Cole331708b2004-08-09 04:51:41 +0000200class SocketPairTest(unittest.TestCase, ThreadableTest):
201
202 def __init__(self, methodName='runTest'):
203 unittest.TestCase.__init__(self, methodName=methodName)
204 ThreadableTest.__init__(self)
205
206 def setUp(self):
207 self.serv, self.cli = socket.socketpair()
208
209 def tearDown(self):
210 self.serv.close()
211 self.serv = None
212
213 def clientSetUp(self):
214 pass
215
216 def clientTearDown(self):
217 self.cli.close()
218 self.cli = None
219 ThreadableTest.clientTearDown(self)
220
Tim Peters494aaee2004-08-09 18:54:11 +0000221
Guido van Rossum24e4af82002-06-12 19:18:08 +0000222#######################################################################
223## Begin Tests
224
225class GeneralModuleTests(unittest.TestCase):
226
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000227 def test_repr(self):
228 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
229 self.assert_(repr(s).startswith("<socket.socket object"))
230
Raymond Hettinger027bb632004-05-31 03:09:25 +0000231 def test_weakref(self):
232 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
233 p = proxy(s)
234 self.assertEqual(p.fileno(), s.fileno())
235 s.close()
236 s = None
237 try:
238 p.fileno()
239 except ReferenceError:
240 pass
241 else:
242 self.fail('Socket proxy still exists')
243
Guido van Rossum24e4af82002-06-12 19:18:08 +0000244 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000245 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000246 def raise_error(*args, **kwargs):
247 raise socket.error
248 def raise_herror(*args, **kwargs):
249 raise socket.herror
250 def raise_gaierror(*args, **kwargs):
251 raise socket.gaierror
252 self.failUnlessRaises(socket.error, raise_error,
253 "Error raising socket exception.")
254 self.failUnlessRaises(socket.error, raise_herror,
255 "Error raising socket exception.")
256 self.failUnlessRaises(socket.error, raise_gaierror,
257 "Error raising socket exception.")
258
259 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000260 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000261 socket.AF_INET
262 socket.SOCK_STREAM
263 socket.SOCK_DGRAM
264 socket.SOCK_RAW
265 socket.SOCK_RDM
266 socket.SOCK_SEQPACKET
267 socket.SOL_SOCKET
268 socket.SO_REUSEADDR
269
Guido van Rossum654c11e2002-06-13 20:24:17 +0000270 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000271 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000272 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000273 try:
274 ip = socket.gethostbyname(hostname)
275 except socket.error:
276 # Probably name lookup wasn't set up right; skip this test
277 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000278 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000279 try:
280 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
281 except socket.error:
282 # Probably a similar problem as above; skip this test
283 return
Brett Cannon01668a12005-03-11 00:04:17 +0000284 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000286 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000287 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000288
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000289 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000290 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000291 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000292 try:
293 # On some versions, this loses a reference
294 orig = sys.getrefcount(__name__)
295 socket.getnameinfo(__name__,0)
296 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000297 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000298 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000299
Guido van Rossum24e4af82002-06-12 19:18:08 +0000300 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000301 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000302 try:
303 # On some versions, this crashes the interpreter.
304 socket.getnameinfo(('x', 0, 0, 0), 0)
305 except socket.error:
306 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000307
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000308 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000309 # This just checks that htons etc. are their own inverse,
310 # when looking at the lower 16 or 32 bits.
311 sizes = {socket.htonl: 32, socket.ntohl: 32,
312 socket.htons: 16, socket.ntohs: 16}
313 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000314 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000315 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
316 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000317
Guido van Rossuma2627af2002-09-14 00:58:46 +0000318 swapped = func(mask)
319 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000320 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000321
Guido van Rossum018919a2007-01-15 00:07:32 +0000322 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000323 good_values = [ 1, 2, 3, 1, 2, 3 ]
324 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000325 for k in good_values:
326 socket.ntohl(k)
327 socket.ntohs(k)
328 socket.htonl(k)
329 socket.htons(k)
330 for k in bad_values:
331 self.assertRaises(OverflowError, socket.ntohl, k)
332 self.assertRaises(OverflowError, socket.ntohs, k)
333 self.assertRaises(OverflowError, socket.htonl, k)
334 self.assertRaises(OverflowError, socket.htons, k)
335
Barry Warsaw11b91a02004-06-28 00:50:43 +0000336 def testGetServBy(self):
337 eq = self.assertEqual
338 # Find one service that exists, then check all the related interfaces.
339 # I've ordered this by protocols that have both a tcp and udp
340 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000341 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000342 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000343 # avoid the 'echo' service on this platform, as there is an
344 # assumption breaking non-standard port/protocol entry
345 services = ('daytime', 'qotd', 'domain')
346 else:
347 services = ('echo', 'daytime', 'domain')
348 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000349 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000350 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000351 break
352 except socket.error:
353 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000354 else:
355 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000356 # Try same call with optional protocol omitted
357 port2 = socket.getservbyname(service)
358 eq(port, port2)
359 # Try udp, but don't barf it it doesn't exist
360 try:
361 udpport = socket.getservbyname(service, 'udp')
362 except socket.error:
363 udpport = None
364 else:
365 eq(udpport, port)
366 # Now make sure the lookup by port returns the same service name
367 eq(socket.getservbyport(port2), service)
368 eq(socket.getservbyport(port, 'tcp'), service)
369 if udpport is not None:
370 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000371
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000372 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000373 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000374 # The default timeout should initially be None
375 self.assertEqual(socket.getdefaulttimeout(), None)
376 s = socket.socket()
377 self.assertEqual(s.gettimeout(), None)
378 s.close()
379
380 # Set the default timeout to 10, and see if it propagates
381 socket.setdefaulttimeout(10)
382 self.assertEqual(socket.getdefaulttimeout(), 10)
383 s = socket.socket()
384 self.assertEqual(s.gettimeout(), 10)
385 s.close()
386
387 # Reset the default timeout to None, and see if it propagates
388 socket.setdefaulttimeout(None)
389 self.assertEqual(socket.getdefaulttimeout(), None)
390 s = socket.socket()
391 self.assertEqual(s.gettimeout(), None)
392 s.close()
393
394 # Check that setting it to an invalid value raises ValueError
395 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
396
397 # Check that setting it to an invalid type raises TypeError
398 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
399
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000400 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000401 if not hasattr(socket, 'inet_pton'):
402 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000403 from socket import inet_aton as f, inet_pton, AF_INET
404 g = lambda a: inet_pton(AF_INET, a)
405
Guido van Rossumb5b22702007-05-18 18:55:53 +0000406 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
407 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
408 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
409 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
410 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000411
Guido van Rossumb5b22702007-05-18 18:55:53 +0000412 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
413 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
414 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
415 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000416
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000417 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000418 if not hasattr(socket, 'inet_pton'):
419 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000420 try:
421 from socket import inet_pton, AF_INET6, has_ipv6
422 if not has_ipv6:
423 return
424 except ImportError:
425 return
426 f = lambda a: inet_pton(AF_INET6, a)
427
Guido van Rossum540d9872007-08-17 03:51:09 +0000428 self.assertEquals(b'\x00' * 16, f('::'))
429 self.assertEquals(b'\x00' * 16, f('0::0'))
430 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000431 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000432 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 +0000433 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
434 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000435
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000436 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000437 if not hasattr(socket, 'inet_ntop'):
438 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000439 from socket import inet_ntoa as f, inet_ntop, AF_INET
440 g = lambda a: inet_ntop(AF_INET, a)
441
Guido van Rossumb5b22702007-05-18 18:55:53 +0000442 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
443 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
444 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
445 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000446
Guido van Rossumb5b22702007-05-18 18:55:53 +0000447 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
448 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
449 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000450
451 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000452 if not hasattr(socket, 'inet_ntop'):
453 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000454 try:
455 from socket import inet_ntop, AF_INET6, has_ipv6
456 if not has_ipv6:
457 return
458 except ImportError:
459 return
460 f = lambda a: inet_ntop(AF_INET6, a)
461
Guido van Rossum540d9872007-08-17 03:51:09 +0000462 self.assertEquals('::', f(b'\x00' * 16))
463 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000464 self.assertEquals(
465 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000466 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 +0000467 )
468
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000469 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000470
Guido van Rossum24e4af82002-06-12 19:18:08 +0000471 def testSockName(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000472 # Testing getsockname()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000473 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000474 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000475 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
477 # it reasonable to get the host's addr in addition to 0.0.0.0.
478 # At least for eCos. This is required for the S/390 to pass.
479 my_ip_addr = socket.gethostbyname(socket.gethostname())
480 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
481 self.assertEqual(name[1], PORT+1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000482
483 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000484 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000485 # We know a socket should start without reuse==0
486 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
487 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000488 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000489
490 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000491 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000492 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
493 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
494 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000495 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000496
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000497 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000498 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000499 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
500 sock.settimeout(1)
501 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000502 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000503
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000504 def testNewAttributes(self):
505 # testing .family, .type and .protocol
506 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
507 self.assertEqual(sock.family, socket.AF_INET)
508 self.assertEqual(sock.type, socket.SOCK_STREAM)
509 self.assertEqual(sock.proto, 0)
510 sock.close()
511
Christian Heimesfaf2f632008-01-06 16:59:19 +0000512 def test_sock_ioctl(self):
513 if os.name != "nt":
514 return
515 self.assert_(hasattr(socket.socket, 'ioctl'))
516 self.assert_(hasattr(socket, 'SIO_RCVALL'))
517 self.assert_(hasattr(socket, 'RCVALL_ON'))
518 self.assert_(hasattr(socket, 'RCVALL_OFF'))
519
520
Guido van Rossum24e4af82002-06-12 19:18:08 +0000521class BasicTCPTest(SocketConnectedTest):
522
523 def __init__(self, methodName='runTest'):
524 SocketConnectedTest.__init__(self, methodName=methodName)
525
526 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000527 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000528 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000529 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000530
531 def _testRecv(self):
532 self.serv_conn.send(MSG)
533
534 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000535 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000536 seg1 = self.cli_conn.recv(len(MSG) - 3)
537 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000538 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000539 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000540
541 def _testOverFlowRecv(self):
542 self.serv_conn.send(MSG)
543
544 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000545 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000546 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000547 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000548
549 def _testRecvFrom(self):
550 self.serv_conn.send(MSG)
551
552 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000553 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000554 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
555 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000556 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000557 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000558
559 def _testOverFlowRecvFrom(self):
560 self.serv_conn.send(MSG)
561
562 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000563 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000564 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000565 while 1:
566 read = self.cli_conn.recv(1024)
567 if not read:
568 break
Guido van Rossume531e292002-08-08 20:28:34 +0000569 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000570 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000571
572 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000573 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000574 self.serv_conn.sendall(big_chunk)
575
576 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000577 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000578 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000579 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000580 fd = self.cli_conn.fileno()
581 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
582 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000583 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000584
585 def _testFromFd(self):
586 self.serv_conn.send(MSG)
587
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000588 def testDup(self):
589 # Testing dup()
590 sock = self.cli_conn.dup()
591 msg = sock.recv(1024)
592 self.assertEqual(msg, MSG)
593
594 def _testDup(self):
595 self.serv_conn.send(MSG)
596
Guido van Rossum24e4af82002-06-12 19:18:08 +0000597 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000598 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000599 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000600 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000601
602 def _testShutdown(self):
603 self.serv_conn.send(MSG)
604 self.serv_conn.shutdown(2)
605
606class BasicUDPTest(ThreadedUDPSocketTest):
607
608 def __init__(self, methodName='runTest'):
609 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
610
611 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000612 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000613 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000614 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000615
616 def _testSendtoAndRecv(self):
617 self.cli.sendto(MSG, 0, (HOST, PORT))
618
Guido van Rossum1c938012002-06-12 21:17:20 +0000619 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000620 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000621 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000622 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000623
Guido van Rossum1c938012002-06-12 21:17:20 +0000624 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000625 self.cli.sendto(MSG, 0, (HOST, PORT))
626
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 def testRecvFromNegative(self):
628 # Negative lengths passed to recvfrom should give ValueError.
629 self.assertRaises(ValueError, self.serv.recvfrom, -1)
630
631 def _testRecvFromNegative(self):
632 self.cli.sendto(MSG, 0, (HOST, PORT))
633
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634class TCPCloserTest(ThreadedTCPSocketTest):
635
636 def testClose(self):
637 conn, addr = self.serv.accept()
638 conn.close()
639
640 sd = self.cli
641 read, write, err = select.select([sd], [], [], 1.0)
642 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000643 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000644
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000645 # Calling close() many times should be safe.
646 conn.close()
647 conn.close()
648
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649 def _testClose(self):
650 self.cli.connect((HOST, PORT))
651 time.sleep(1.0)
652
Dave Cole331708b2004-08-09 04:51:41 +0000653class BasicSocketPairTest(SocketPairTest):
654
655 def __init__(self, methodName='runTest'):
656 SocketPairTest.__init__(self, methodName=methodName)
657
658 def testRecv(self):
659 msg = self.serv.recv(1024)
660 self.assertEqual(msg, MSG)
661
662 def _testRecv(self):
663 self.cli.send(MSG)
664
665 def testSend(self):
666 self.serv.send(MSG)
667
668 def _testSend(self):
669 msg = self.cli.recv(1024)
670 self.assertEqual(msg, MSG)
671
Guido van Rossum24e4af82002-06-12 19:18:08 +0000672class NonBlockingTCPTests(ThreadedTCPSocketTest):
673
674 def __init__(self, methodName='runTest'):
675 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
676
677 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000678 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000679 self.serv.setblocking(0)
680 start = time.time()
681 try:
682 self.serv.accept()
683 except socket.error:
684 pass
685 end = time.time()
686 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
687
688 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000689 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000690
Guido van Rossum24e4af82002-06-12 19:18:08 +0000691 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000692 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000693 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000694 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000695 conn, addr = self.serv.accept()
696 except socket.error:
697 pass
698 else:
699 self.fail("Error trying to do non-blocking accept.")
700 read, write, err = select.select([self.serv], [], [])
701 if self.serv in read:
702 conn, addr = self.serv.accept()
703 else:
704 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000705
Guido van Rossum24e4af82002-06-12 19:18:08 +0000706 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000707 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000708 self.cli.connect((HOST, PORT))
709
710 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000711 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000712 conn, addr = self.serv.accept()
713
714 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000715 self.cli.settimeout(10)
716 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000717
718 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000719 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000720 conn, addr = self.serv.accept()
721 conn.setblocking(0)
722 try:
723 msg = conn.recv(len(MSG))
724 except socket.error:
725 pass
726 else:
727 self.fail("Error trying to do non-blocking recv.")
728 read, write, err = select.select([conn], [], [])
729 if conn in read:
730 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000731 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732 else:
733 self.fail("Error during select call to non-blocking socket.")
734
735 def _testRecv(self):
736 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000737 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000738 self.cli.send(MSG)
739
740class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000741 """Unit tests for the object returned by socket.makefile()
742
743 self.serv_file is the io object returned by makefile() on
744 the client connection. You can read from this file to
745 get output from the server.
746
747 self.cli_file is the io object returned by makefile() on the
748 server connection. You can write to this file to send output
749 to the client.
750 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751
Guido van Rossume9f66142002-08-07 15:46:19 +0000752 bufsize = -1 # Use default buffer size
753
Guido van Rossum24e4af82002-06-12 19:18:08 +0000754 def __init__(self, methodName='runTest'):
755 SocketConnectedTest.__init__(self, methodName=methodName)
756
757 def setUp(self):
758 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000759 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000760
761 def tearDown(self):
762 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000763 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764 self.serv_file = None
765 SocketConnectedTest.tearDown(self)
766
767 def clientSetUp(self):
768 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000769 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000770
771 def clientTearDown(self):
772 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000773 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000774 self.cli_file = None
775 SocketConnectedTest.clientTearDown(self)
776
777 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000778 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000779 first_seg = self.serv_file.read(len(MSG)-3)
780 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000781 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000782 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000783
784 def _testSmallRead(self):
785 self.cli_file.write(MSG)
786 self.cli_file.flush()
787
Guido van Rossum8c943832002-08-08 01:00:28 +0000788 def testFullRead(self):
789 # read until EOF
790 msg = self.serv_file.read()
791 self.assertEqual(msg, MSG)
792
793 def _testFullRead(self):
794 self.cli_file.write(MSG)
795 self.cli_file.close()
796
Guido van Rossum24e4af82002-06-12 19:18:08 +0000797 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000798 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000799 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000800 while 1:
801 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000802 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000803 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000804 buf += char
805 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000806
807 def _testUnbufferedRead(self):
808 self.cli_file.write(MSG)
809 self.cli_file.flush()
810
811 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000812 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000813 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000814 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000815
816 def _testReadline(self):
817 self.cli_file.write(MSG)
818 self.cli_file.flush()
819
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000820 def testCloseAfterMakefile(self):
821 # The file returned by makefile should keep the socket open.
822 self.cli_conn.close()
823 # read until EOF
824 msg = self.serv_file.read()
825 self.assertEqual(msg, MSG)
826
827 def _testCloseAfterMakefile(self):
828 self.cli_file.write(MSG)
829 self.cli_file.flush()
830
831 def testMakefileAfterMakefileClose(self):
832 self.serv_file.close()
833 msg = self.cli_conn.recv(len(MSG))
834 self.assertEqual(msg, MSG)
835
836 def _testMakefileAfterMakefileClose(self):
837 self.cli_file.write(MSG)
838 self.cli_file.flush()
839
Tim Peters116d83c2004-03-28 02:20:45 +0000840 def testClosedAttr(self):
841 self.assert_(not self.serv_file.closed)
842
843 def _testClosedAttr(self):
844 self.assert_(not self.cli_file.closed)
845
Guido van Rossume9f66142002-08-07 15:46:19 +0000846class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
847
848 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000849
Guido van Rossume9f66142002-08-07 15:46:19 +0000850 In this case (and in this case only), it should be possible to
851 create a file object, read a line from it, create another file
852 object, read another line from it, without loss of data in the
853 first file object's buffer. Note that httplib relies on this
854 when reading multiple requests from the same socket."""
855
856 bufsize = 0 # Use unbuffered mode
857
858 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000859 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000860 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000861 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000862 self.serv_file = self.cli_conn.makefile('rb', 0)
863 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000864 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000865
866 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000867 self.cli_file.write(b"A. " + MSG)
868 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000869 self.cli_file.flush()
870
Guido van Rossum8c943832002-08-08 01:00:28 +0000871class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
872
873 bufsize = 1 # Default-buffered for reading; line-buffered for writing
874
875
876class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
877
878 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000879
Thomas Woutersb2137042007-02-01 18:02:27 +0000880
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881class NetworkConnectionTest(object):
882 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000883
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 def clientSetUp(self):
885 self.cli = socket.create_connection((HOST, PORT))
886 self.serv_conn = self.cli
887
888class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
889 """Tests that NetworkConnection does not break existing TCP functionality.
890 """
891
892class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000893
Guido van Rossumd8faa362007-04-27 19:54:29 +0000894 def testWithoutServer(self):
895 self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
896
897class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
898
899 def __init__(self, methodName='runTest'):
900 SocketTCPTest.__init__(self, methodName=methodName)
901 ThreadableTest.__init__(self)
902
903 def clientSetUp(self):
904 pass
905
906 def clientTearDown(self):
907 self.cli.close()
908 self.cli = None
909 ThreadableTest.clientTearDown(self)
910
911 def _justAccept(self):
912 conn, addr = self.serv.accept()
913
914 testFamily = _justAccept
915 def _testFamily(self):
916 self.cli = socket.create_connection((HOST, PORT), timeout=30)
917 self.assertEqual(self.cli.family, 2)
918
919 testTimeoutDefault = _justAccept
920 def _testTimeoutDefault(self):
921 self.cli = socket.create_connection((HOST, PORT))
922 self.assertTrue(self.cli.gettimeout() is None)
923
924 testTimeoutValueNamed = _justAccept
925 def _testTimeoutValueNamed(self):
926 self.cli = socket.create_connection((HOST, PORT), timeout=30)
927 self.assertEqual(self.cli.gettimeout(), 30)
928
929 testTimeoutValueNonamed = _justAccept
930 def _testTimeoutValueNonamed(self):
931 self.cli = socket.create_connection((HOST, PORT), 30)
932 self.assertEqual(self.cli.gettimeout(), 30)
933
934 testTimeoutNone = _justAccept
935 def _testTimeoutNone(self):
936 previous = socket.getdefaulttimeout()
937 socket.setdefaulttimeout(30)
938 try:
939 self.cli = socket.create_connection((HOST, PORT), timeout=None)
940 finally:
941 socket.setdefaulttimeout(previous)
942 self.assertEqual(self.cli.gettimeout(), 30)
943
944
945class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
946
947 def __init__(self, methodName='runTest'):
948 SocketTCPTest.__init__(self, methodName=methodName)
949 ThreadableTest.__init__(self)
950
951 def clientSetUp(self):
952 pass
953
954 def clientTearDown(self):
955 self.cli.close()
956 self.cli = None
957 ThreadableTest.clientTearDown(self)
958
959 def testInsideTimeout(self):
960 conn, addr = self.serv.accept()
961 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000962 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963 testOutsideTimeout = testInsideTimeout
964
965 def _testInsideTimeout(self):
966 self.cli = sock = socket.create_connection((HOST, PORT))
967 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000968 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969
970 def _testOutsideTimeout(self):
971 self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
972 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
973
974
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000975class TCPTimeoutTest(SocketTCPTest):
976
977 def testTCPTimeout(self):
978 def raise_timeout(*args, **kwargs):
979 self.serv.settimeout(1.0)
980 self.serv.accept()
981 self.failUnlessRaises(socket.timeout, raise_timeout,
982 "Error generating a timeout exception (TCP)")
983
984 def testTimeoutZero(self):
985 ok = False
986 try:
987 self.serv.settimeout(0.0)
988 foo = self.serv.accept()
989 except socket.timeout:
990 self.fail("caught timeout instead of error (TCP)")
991 except socket.error:
992 ok = True
993 except:
994 self.fail("caught unexpected exception (TCP)")
995 if not ok:
996 self.fail("accept() returned success when we did not expect it")
997
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998 def testInterruptedTimeout(self):
999 # XXX I don't know how to do this test on MSWindows or any other
1000 # plaform that doesn't support signal.alarm() or os.kill(), though
1001 # the bug should have existed on all platforms.
1002 if not hasattr(signal, "alarm"):
1003 return # can only test on *nix
1004 self.serv.settimeout(5.0) # must be longer than alarm
1005 class Alarm(Exception):
1006 pass
1007 def alarm_handler(signal, frame):
1008 raise Alarm
1009 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1010 try:
1011 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1012 try:
1013 foo = self.serv.accept()
1014 except socket.timeout:
1015 self.fail("caught timeout instead of Alarm")
1016 except Alarm:
1017 pass
1018 except:
1019 self.fail("caught other exception instead of Alarm")
1020 else:
1021 self.fail("nothing caught")
1022 signal.alarm(0) # shut off alarm
1023 except Alarm:
1024 self.fail("got Alarm in wrong place")
1025 finally:
1026 # no alarm can be pending. Safe to restore old handler.
1027 signal.signal(signal.SIGALRM, old_alarm)
1028
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001029class UDPTimeoutTest(SocketTCPTest):
1030
1031 def testUDPTimeout(self):
1032 def raise_timeout(*args, **kwargs):
1033 self.serv.settimeout(1.0)
1034 self.serv.recv(1024)
1035 self.failUnlessRaises(socket.timeout, raise_timeout,
1036 "Error generating a timeout exception (UDP)")
1037
1038 def testTimeoutZero(self):
1039 ok = False
1040 try:
1041 self.serv.settimeout(0.0)
1042 foo = self.serv.recv(1024)
1043 except socket.timeout:
1044 self.fail("caught timeout instead of error (UDP)")
1045 except socket.error:
1046 ok = True
1047 except:
1048 self.fail("caught unexpected exception (UDP)")
1049 if not ok:
1050 self.fail("recv() returned success when we did not expect it")
1051
1052class TestExceptions(unittest.TestCase):
1053
1054 def testExceptionTree(self):
1055 self.assert_(issubclass(socket.error, Exception))
1056 self.assert_(issubclass(socket.herror, socket.error))
1057 self.assert_(issubclass(socket.gaierror, socket.error))
1058 self.assert_(issubclass(socket.timeout, socket.error))
1059
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001060class TestLinuxAbstractNamespace(unittest.TestCase):
1061
1062 UNIX_PATH_MAX = 108
1063
1064 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001065 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001066 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1067 s1.bind(address)
1068 s1.listen(1)
1069 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1070 s2.connect(s1.getsockname())
1071 s1.accept()
1072 self.assertEqual(s1.getsockname(), address)
1073 self.assertEqual(s2.getpeername(), address)
1074
1075 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001076 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001077 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1078 s.bind(address)
1079 self.assertEqual(s.getsockname(), address)
1080
1081 def testNameOverflow(self):
1082 address = "\x00" + "h" * self.UNIX_PATH_MAX
1083 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1084 self.assertRaises(socket.error, s.bind, address)
1085
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001086
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087class BufferIOTest(SocketConnectedTest):
1088 """
1089 Test the buffer versions of socket.recv() and socket.send().
1090 """
1091 def __init__(self, methodName='runTest'):
1092 SocketConnectedTest.__init__(self, methodName=methodName)
1093
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001094 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001095 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001096 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001098 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099 self.assertEqual(msg, MSG)
1100
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001101 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001102 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103 self.serv_conn.send(buf)
1104
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001105 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001106 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001107 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001108 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001109 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 self.assertEqual(msg, MSG)
1111
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001112 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001113 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 self.serv_conn.send(buf)
1115
Christian Heimes043d6f62008-01-07 17:19:16 +00001116
1117TIPC_STYPE = 2000
1118TIPC_LOWER = 200
1119TIPC_UPPER = 210
1120
1121def isTipcAvailable():
1122 """Check if the TIPC module is loaded
1123
1124 The TIPC module is not loaded automatically on Ubuntu and probably
1125 other Linux distros.
1126 """
1127 if not hasattr(socket, "AF_TIPC"):
1128 return False
1129 if not os.path.isfile("/proc/modules"):
1130 return False
1131 with open("/proc/modules") as f:
1132 for line in f:
1133 if line.startswith("tipc "):
1134 return True
Christian Heimes2380ac72008-01-09 00:17:24 +00001135 if test_support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001136 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1137 return False
1138
1139class TIPCTest (unittest.TestCase):
1140 def testRDM(self):
1141 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1142 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1143
1144 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1145 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1146 TIPC_LOWER, TIPC_UPPER)
1147 srv.bind(srvaddr)
1148
1149 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1150 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1151 cli.sendto(MSG, sendaddr)
1152
1153 msg, recvaddr = srv.recvfrom(1024)
1154
1155 self.assertEqual(cli.getsockname(), recvaddr)
1156 self.assertEqual(msg, MSG)
1157
1158
1159class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1160 def __init__(self, methodName = 'runTest'):
1161 unittest.TestCase.__init__(self, methodName = methodName)
1162 ThreadableTest.__init__(self)
1163
1164 def setUp(self):
1165 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1166 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1167 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1168 TIPC_LOWER, TIPC_UPPER)
1169 self.srv.bind(srvaddr)
1170 self.srv.listen(5)
1171 self.serverExplicitReady()
1172 self.conn, self.connaddr = self.srv.accept()
1173
1174 def clientSetUp(self):
1175 # The is a hittable race between serverExplicitReady() and the
1176 # accept() call; sleep a little while to avoid it, otherwise
1177 # we could get an exception
1178 time.sleep(0.1)
1179 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1180 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1181 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1182 self.cli.connect(addr)
1183 self.cliaddr = self.cli.getsockname()
1184
1185 def testStream(self):
1186 msg = self.conn.recv(1024)
1187 self.assertEqual(msg, MSG)
1188 self.assertEqual(self.cliaddr, self.connaddr)
1189
1190 def _testStream(self):
1191 self.cli.send(MSG)
1192 self.cli.close()
1193
1194
Guido van Rossumb995eb72002-07-31 16:08:40 +00001195def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001196 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001198 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001199 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001200
1201 tests.extend([
1202 NonBlockingTCPTests,
1203 FileObjectClassTestCase,
1204 UnbufferedFileObjectClassTestCase,
1205 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001206 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 NetworkConnectionNoServer,
1208 NetworkConnectionAttributesTest,
1209 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001210 ])
Dave Cole331708b2004-08-09 04:51:41 +00001211 if hasattr(socket, "socketpair"):
1212 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001213 if sys.platform == 'linux2':
1214 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001215 if isTipcAvailable():
1216 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001217 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001218
1219 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001220 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001221 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001222
1223if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001224 test_main()