blob: bc31620decbb606bee14d992eb4634c01ff6e913 [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
121 if not self.queue.empty():
122 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 Rossum24e4af82002-06-12 19:18:08 +0000291 import sys
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:
1020 self.fail("caught other exception instead of Alarm")
1021 else:
1022 self.fail("nothing caught")
1023 signal.alarm(0) # shut off alarm
1024 except Alarm:
1025 self.fail("got Alarm in wrong place")
1026 finally:
1027 # no alarm can be pending. Safe to restore old handler.
1028 signal.signal(signal.SIGALRM, old_alarm)
1029
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001030class UDPTimeoutTest(SocketTCPTest):
1031
1032 def testUDPTimeout(self):
1033 def raise_timeout(*args, **kwargs):
1034 self.serv.settimeout(1.0)
1035 self.serv.recv(1024)
1036 self.failUnlessRaises(socket.timeout, raise_timeout,
1037 "Error generating a timeout exception (UDP)")
1038
1039 def testTimeoutZero(self):
1040 ok = False
1041 try:
1042 self.serv.settimeout(0.0)
1043 foo = self.serv.recv(1024)
1044 except socket.timeout:
1045 self.fail("caught timeout instead of error (UDP)")
1046 except socket.error:
1047 ok = True
1048 except:
1049 self.fail("caught unexpected exception (UDP)")
1050 if not ok:
1051 self.fail("recv() returned success when we did not expect it")
1052
1053class TestExceptions(unittest.TestCase):
1054
1055 def testExceptionTree(self):
1056 self.assert_(issubclass(socket.error, Exception))
1057 self.assert_(issubclass(socket.herror, socket.error))
1058 self.assert_(issubclass(socket.gaierror, socket.error))
1059 self.assert_(issubclass(socket.timeout, socket.error))
1060
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001061class TestLinuxAbstractNamespace(unittest.TestCase):
1062
1063 UNIX_PATH_MAX = 108
1064
1065 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001066 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1068 s1.bind(address)
1069 s1.listen(1)
1070 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1071 s2.connect(s1.getsockname())
1072 s1.accept()
1073 self.assertEqual(s1.getsockname(), address)
1074 self.assertEqual(s2.getpeername(), address)
1075
1076 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001077 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1079 s.bind(address)
1080 self.assertEqual(s.getsockname(), address)
1081
1082 def testNameOverflow(self):
1083 address = "\x00" + "h" * self.UNIX_PATH_MAX
1084 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1085 self.assertRaises(socket.error, s.bind, address)
1086
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001087
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088class BufferIOTest(SocketConnectedTest):
1089 """
1090 Test the buffer versions of socket.recv() and socket.send().
1091 """
1092 def __init__(self, methodName='runTest'):
1093 SocketConnectedTest.__init__(self, methodName=methodName)
1094
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001095 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001096 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001097 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001098 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001099 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 self.assertEqual(msg, MSG)
1101
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001102 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001103 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001104 self.serv_conn.send(buf)
1105
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001106 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001107 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001108 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001110 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111 self.assertEqual(msg, MSG)
1112
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001113 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001114 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 self.serv_conn.send(buf)
1116
Christian Heimes043d6f62008-01-07 17:19:16 +00001117
1118TIPC_STYPE = 2000
1119TIPC_LOWER = 200
1120TIPC_UPPER = 210
1121
1122def isTipcAvailable():
1123 """Check if the TIPC module is loaded
1124
1125 The TIPC module is not loaded automatically on Ubuntu and probably
1126 other Linux distros.
1127 """
1128 if not hasattr(socket, "AF_TIPC"):
1129 return False
1130 if not os.path.isfile("/proc/modules"):
1131 return False
1132 with open("/proc/modules") as f:
1133 for line in f:
1134 if line.startswith("tipc "):
1135 return True
1136 if test_support.debug:
1137 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1138 return False
1139
1140class TIPCTest (unittest.TestCase):
1141 def testRDM(self):
1142 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1143 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1144
1145 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1146 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1147 TIPC_LOWER, TIPC_UPPER)
1148 srv.bind(srvaddr)
1149
1150 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1151 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1152 cli.sendto(MSG, sendaddr)
1153
1154 msg, recvaddr = srv.recvfrom(1024)
1155
1156 self.assertEqual(cli.getsockname(), recvaddr)
1157 self.assertEqual(msg, MSG)
1158
1159
1160class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1161 def __init__(self, methodName = 'runTest'):
1162 unittest.TestCase.__init__(self, methodName = methodName)
1163 ThreadableTest.__init__(self)
1164
1165 def setUp(self):
1166 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1167 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1168 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1169 TIPC_LOWER, TIPC_UPPER)
1170 self.srv.bind(srvaddr)
1171 self.srv.listen(5)
1172 self.serverExplicitReady()
1173 self.conn, self.connaddr = self.srv.accept()
1174
1175 def clientSetUp(self):
1176 # The is a hittable race between serverExplicitReady() and the
1177 # accept() call; sleep a little while to avoid it, otherwise
1178 # we could get an exception
1179 time.sleep(0.1)
1180 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1181 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1182 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1183 self.cli.connect(addr)
1184 self.cliaddr = self.cli.getsockname()
1185
1186 def testStream(self):
1187 msg = self.conn.recv(1024)
1188 self.assertEqual(msg, MSG)
1189 self.assertEqual(self.cliaddr, self.connaddr)
1190
1191 def _testStream(self):
1192 self.cli.send(MSG)
1193 self.cli.close()
1194
1195
Guido van Rossumb995eb72002-07-31 16:08:40 +00001196def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001197 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001199 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001200 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001201
1202 tests.extend([
1203 NonBlockingTCPTests,
1204 FileObjectClassTestCase,
1205 UnbufferedFileObjectClassTestCase,
1206 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001207 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208 NetworkConnectionNoServer,
1209 NetworkConnectionAttributesTest,
1210 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001211 ])
Dave Cole331708b2004-08-09 04:51:41 +00001212 if hasattr(socket, "socketpair"):
1213 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001214 if sys.platform == 'linux2':
1215 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001216 if isTipcAvailable():
1217 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001218 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001219
1220 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001221 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001223
1224if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001225 test_main()