blob: f4abffaa35b56ddf1c7bcc94950a0f683106efaa [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test import test_support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Barry Warsawcf3d4b51997-01-03 20:03:32 +00006import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00007import select
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import thread, threading
Christian Heimesbbe741d2008-03-28 10:53:29 +00009import time
10import traceback
Guido van Rossum24e4af82002-06-12 19:18:08 +000011import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000012import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000013import os
14import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000015from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000016import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000017
Neal Norwitzdb4115f2008-03-31 04:20:05 +000018# Temporary hack to see why test_socket hangs on one buildbot
19if os.environ.get('COMPUTERNAME') == "GRAPE":
20 def verbose_write(arg):
21 print(arg, file=sys.__stdout__)
22else:
23 def verbose_write(arg):
24 pass
25
Guido van Rossum24e4af82002-06-12 19:18:08 +000026PORT = 50007
27HOST = 'localhost'
Guido van Rossum7d0a8262007-05-21 23:13:11 +000028MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000029
Guido van Rossum24e4af82002-06-12 19:18:08 +000030class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000031
Guido van Rossum24e4af82002-06-12 19:18:08 +000032 def setUp(self):
Neal Norwitzdb4115f2008-03-31 04:20:05 +000033 verbose_write(self)
Guido van Rossum24e4af82002-06-12 19:18:08 +000034 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
35 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Neal Norwitzdb4115f2008-03-31 04:20:05 +000036 verbose_write(str(self) + " socket created")
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037 global PORT
38 PORT = test_support.bind_port(self.serv, HOST, PORT)
Neal Norwitzdb4115f2008-03-31 04:20:05 +000039 verbose_write(str(self) + " start listening")
Guido van Rossum24e4af82002-06-12 19:18:08 +000040 self.serv.listen(1)
Neal Norwitzdb4115f2008-03-31 04:20:05 +000041 verbose_write(str(self) + " started")
Barry Warsawcf3d4b51997-01-03 20:03:32 +000042
Guido van Rossum24e4af82002-06-12 19:18:08 +000043 def tearDown(self):
Neal Norwitzdb4115f2008-03-31 04:20:05 +000044 verbose_write(str(self) + " close")
Guido van Rossum24e4af82002-06-12 19:18:08 +000045 self.serv.close()
46 self.serv = None
Neal Norwitzdb4115f2008-03-31 04:20:05 +000047 verbose_write(str(self) + " done")
Barry Warsawcf3d4b51997-01-03 20:03:32 +000048
Guido van Rossum24e4af82002-06-12 19:18:08 +000049class SocketUDPTest(unittest.TestCase):
50
51 def setUp(self):
52 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
53 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054 global PORT
55 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000056
57 def tearDown(self):
58 self.serv.close()
59 self.serv = None
60
61class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000062 """Threadable Test class
63
64 The ThreadableTest class makes it easy to create a threaded
65 client/server pair from an existing unit test. To create a
66 new threaded class from an existing unit test, use multiple
67 inheritance:
68
69 class NewClass (OldClass, ThreadableTest):
70 pass
71
72 This class defines two new fixture functions with obvious
73 purposes for overriding:
74
75 clientSetUp ()
76 clientTearDown ()
77
78 Any new test functions within the class must then define
79 tests in pairs, where the test name is preceeded with a
80 '_' to indicate the client portion of the test. Ex:
81
82 def testFoo(self):
83 # Server portion
84
85 def _testFoo(self):
86 # Client portion
87
88 Any exceptions raised by the clients during their tests
89 are caught and transferred to the main thread to alert
90 the testing framework.
91
92 Note, the server setup function cannot call any blocking
93 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000094 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000095 the blocking call (such as in setting up a client/server
96 connection and performing the accept() in setUp().
97 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000098
99 def __init__(self):
100 # Swap the true setup function
101 self.__setUp = self.setUp
102 self.__tearDown = self.tearDown
103 self.setUp = self._setUp
104 self.tearDown = self._tearDown
105
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000106 def serverExplicitReady(self):
107 """This method allows the server to explicitly indicate that
108 it wants the client thread to proceed. This is useful if the
109 server is about to execute a blocking routine that is
110 dependent upon the client thread during its setup routine."""
111 self.server_ready.set()
112
Guido van Rossum24e4af82002-06-12 19:18:08 +0000113 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000114 self.server_ready = threading.Event()
115 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000116 self.done = threading.Event()
117 self.queue = Queue.Queue(1)
118
119 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000120 methodname = self.id()
121 i = methodname.rfind('.')
122 methodname = methodname[i+1:]
123 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000124 self.client_thread = thread.start_new_thread(
125 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000126
127 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000128 if not self.server_ready.isSet():
129 self.server_ready.set()
130 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000131
132 def _tearDown(self):
133 self.__tearDown()
134 self.done.wait()
135
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000136 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000137 msg = self.queue.get()
138 self.fail(msg)
139
140 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000141 self.server_ready.wait()
142 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000143 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000144 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000145 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000146 try:
147 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000148 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000149 self.queue.put(strerror)
150 self.clientTearDown()
151
152 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000153 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000154
155 def clientTearDown(self):
156 self.done.set()
157 thread.exit()
158
159class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
160
161 def __init__(self, methodName='runTest'):
162 SocketTCPTest.__init__(self, methodName=methodName)
163 ThreadableTest.__init__(self)
164
165 def clientSetUp(self):
166 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
167
168 def clientTearDown(self):
169 self.cli.close()
170 self.cli = None
171 ThreadableTest.clientTearDown(self)
172
173class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
174
175 def __init__(self, methodName='runTest'):
176 SocketUDPTest.__init__(self, methodName=methodName)
177 ThreadableTest.__init__(self)
178
179 def clientSetUp(self):
180 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
181
182class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000183 """Socket tests for client-server connection.
184
185 self.cli_conn is a client socket connected to the server. The
186 setUp() method guarantees that it is connected to the server.
187 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000188
189 def __init__(self, methodName='runTest'):
190 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
191
192 def setUp(self):
193 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000194 # Indicate explicitly we're ready for the client thread to
195 # proceed and then perform the blocking call to accept
196 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000197 conn, addr = self.serv.accept()
198 self.cli_conn = conn
199
200 def tearDown(self):
201 self.cli_conn.close()
202 self.cli_conn = None
203 ThreadedTCPSocketTest.tearDown(self)
204
205 def clientSetUp(self):
206 ThreadedTCPSocketTest.clientSetUp(self)
207 self.cli.connect((HOST, PORT))
208 self.serv_conn = self.cli
209
210 def clientTearDown(self):
211 self.serv_conn.close()
212 self.serv_conn = None
213 ThreadedTCPSocketTest.clientTearDown(self)
214
Dave Cole331708b2004-08-09 04:51:41 +0000215class SocketPairTest(unittest.TestCase, ThreadableTest):
216
217 def __init__(self, methodName='runTest'):
218 unittest.TestCase.__init__(self, methodName=methodName)
219 ThreadableTest.__init__(self)
220
221 def setUp(self):
222 self.serv, self.cli = socket.socketpair()
223
224 def tearDown(self):
225 self.serv.close()
226 self.serv = None
227
228 def clientSetUp(self):
229 pass
230
231 def clientTearDown(self):
232 self.cli.close()
233 self.cli = None
234 ThreadableTest.clientTearDown(self)
235
Tim Peters494aaee2004-08-09 18:54:11 +0000236
Guido van Rossum24e4af82002-06-12 19:18:08 +0000237#######################################################################
238## Begin Tests
239
240class GeneralModuleTests(unittest.TestCase):
241
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000242 def test_repr(self):
243 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
244 self.assert_(repr(s).startswith("<socket.socket object"))
245
Raymond Hettinger027bb632004-05-31 03:09:25 +0000246 def test_weakref(self):
247 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
248 p = proxy(s)
249 self.assertEqual(p.fileno(), s.fileno())
250 s.close()
251 s = None
252 try:
253 p.fileno()
254 except ReferenceError:
255 pass
256 else:
257 self.fail('Socket proxy still exists')
258
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000260 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000261 def raise_error(*args, **kwargs):
262 raise socket.error
263 def raise_herror(*args, **kwargs):
264 raise socket.herror
265 def raise_gaierror(*args, **kwargs):
266 raise socket.gaierror
267 self.failUnlessRaises(socket.error, raise_error,
268 "Error raising socket exception.")
269 self.failUnlessRaises(socket.error, raise_herror,
270 "Error raising socket exception.")
271 self.failUnlessRaises(socket.error, raise_gaierror,
272 "Error raising socket exception.")
273
274 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000275 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000276 socket.AF_INET
277 socket.SOCK_STREAM
278 socket.SOCK_DGRAM
279 socket.SOCK_RAW
280 socket.SOCK_RDM
281 socket.SOCK_SEQPACKET
282 socket.SOL_SOCKET
283 socket.SO_REUSEADDR
284
Guido van Rossum654c11e2002-06-13 20:24:17 +0000285 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000286 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000287 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000288 try:
289 ip = socket.gethostbyname(hostname)
290 except socket.error:
291 # Probably name lookup wasn't set up right; skip this test
292 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000293 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000294 try:
295 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
296 except socket.error:
297 # Probably a similar problem as above; skip this test
298 return
Brett Cannon01668a12005-03-11 00:04:17 +0000299 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000301 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000303
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000304 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000305 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000306 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000307 try:
308 # On some versions, this loses a reference
309 orig = sys.getrefcount(__name__)
310 socket.getnameinfo(__name__,0)
311 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000312 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000313 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000314
Guido van Rossum24e4af82002-06-12 19:18:08 +0000315 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000316 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000317 try:
318 # On some versions, this crashes the interpreter.
319 socket.getnameinfo(('x', 0, 0, 0), 0)
320 except socket.error:
321 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000322
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000323 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000324 # This just checks that htons etc. are their own inverse,
325 # when looking at the lower 16 or 32 bits.
326 sizes = {socket.htonl: 32, socket.ntohl: 32,
327 socket.htons: 16, socket.ntohs: 16}
328 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000329 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000330 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
331 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000332
Guido van Rossuma2627af2002-09-14 00:58:46 +0000333 swapped = func(mask)
334 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000335 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000336
Guido van Rossum018919a2007-01-15 00:07:32 +0000337 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000338 good_values = [ 1, 2, 3, 1, 2, 3 ]
339 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000340 for k in good_values:
341 socket.ntohl(k)
342 socket.ntohs(k)
343 socket.htonl(k)
344 socket.htons(k)
345 for k in bad_values:
346 self.assertRaises(OverflowError, socket.ntohl, k)
347 self.assertRaises(OverflowError, socket.ntohs, k)
348 self.assertRaises(OverflowError, socket.htonl, k)
349 self.assertRaises(OverflowError, socket.htons, k)
350
Barry Warsaw11b91a02004-06-28 00:50:43 +0000351 def testGetServBy(self):
352 eq = self.assertEqual
353 # Find one service that exists, then check all the related interfaces.
354 # I've ordered this by protocols that have both a tcp and udp
355 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000356 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000357 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000358 # avoid the 'echo' service on this platform, as there is an
359 # assumption breaking non-standard port/protocol entry
360 services = ('daytime', 'qotd', 'domain')
361 else:
362 services = ('echo', 'daytime', 'domain')
363 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000364 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000365 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000366 break
367 except socket.error:
368 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000369 else:
370 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000371 # Try same call with optional protocol omitted
372 port2 = socket.getservbyname(service)
373 eq(port, port2)
374 # Try udp, but don't barf it it doesn't exist
375 try:
376 udpport = socket.getservbyname(service, 'udp')
377 except socket.error:
378 udpport = None
379 else:
380 eq(udpport, port)
381 # Now make sure the lookup by port returns the same service name
382 eq(socket.getservbyport(port2), service)
383 eq(socket.getservbyport(port, 'tcp'), service)
384 if udpport is not None:
385 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000386
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000387 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000388 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000389 # The default timeout should initially be None
390 self.assertEqual(socket.getdefaulttimeout(), None)
391 s = socket.socket()
392 self.assertEqual(s.gettimeout(), None)
393 s.close()
394
395 # Set the default timeout to 10, and see if it propagates
396 socket.setdefaulttimeout(10)
397 self.assertEqual(socket.getdefaulttimeout(), 10)
398 s = socket.socket()
399 self.assertEqual(s.gettimeout(), 10)
400 s.close()
401
402 # Reset the default timeout to None, and see if it propagates
403 socket.setdefaulttimeout(None)
404 self.assertEqual(socket.getdefaulttimeout(), None)
405 s = socket.socket()
406 self.assertEqual(s.gettimeout(), None)
407 s.close()
408
409 # Check that setting it to an invalid value raises ValueError
410 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
411
412 # Check that setting it to an invalid type raises TypeError
413 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
414
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000415 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000416 if not hasattr(socket, 'inet_pton'):
417 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000418 from socket import inet_aton as f, inet_pton, AF_INET
419 g = lambda a: inet_pton(AF_INET, a)
420
Guido van Rossumb5b22702007-05-18 18:55:53 +0000421 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
422 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
423 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
424 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
425 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000426
Guido van Rossumb5b22702007-05-18 18:55:53 +0000427 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
428 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
429 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
430 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000431
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000432 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000433 if not hasattr(socket, 'inet_pton'):
434 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000435 try:
436 from socket import inet_pton, AF_INET6, has_ipv6
437 if not has_ipv6:
438 return
439 except ImportError:
440 return
441 f = lambda a: inet_pton(AF_INET6, a)
442
Guido van Rossum540d9872007-08-17 03:51:09 +0000443 self.assertEquals(b'\x00' * 16, f('::'))
444 self.assertEquals(b'\x00' * 16, f('0::0'))
445 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000446 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000447 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 +0000448 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
449 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000450
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000451 def testStringToIPv4(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 from socket import inet_ntoa as f, inet_ntop, AF_INET
455 g = lambda a: inet_ntop(AF_INET, a)
456
Guido van Rossumb5b22702007-05-18 18:55:53 +0000457 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
458 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
459 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
460 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000461
Guido van Rossumb5b22702007-05-18 18:55:53 +0000462 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
463 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
464 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000465
466 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000467 if not hasattr(socket, 'inet_ntop'):
468 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000469 try:
470 from socket import inet_ntop, AF_INET6, has_ipv6
471 if not has_ipv6:
472 return
473 except ImportError:
474 return
475 f = lambda a: inet_ntop(AF_INET6, a)
476
Guido van Rossum540d9872007-08-17 03:51:09 +0000477 self.assertEquals('::', f(b'\x00' * 16))
478 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000479 self.assertEquals(
480 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000481 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 +0000482 )
483
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000484 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000485
Guido van Rossum24e4af82002-06-12 19:18:08 +0000486 def testSockName(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000487 # Testing getsockname()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000488 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000489 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000490 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000491 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
492 # it reasonable to get the host's addr in addition to 0.0.0.0.
493 # At least for eCos. This is required for the S/390 to pass.
494 my_ip_addr = socket.gethostbyname(socket.gethostname())
495 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
496 self.assertEqual(name[1], PORT+1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000497
498 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000499 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000500 # We know a socket should start without reuse==0
501 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
502 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000503 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000504
505 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000506 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000507 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
508 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
509 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000510 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000511
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000512 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000513 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000514 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
515 sock.settimeout(1)
516 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000517 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000518
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519 def testNewAttributes(self):
520 # testing .family, .type and .protocol
521 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
522 self.assertEqual(sock.family, socket.AF_INET)
523 self.assertEqual(sock.type, socket.SOCK_STREAM)
524 self.assertEqual(sock.proto, 0)
525 sock.close()
526
Christian Heimesfaf2f632008-01-06 16:59:19 +0000527 def test_sock_ioctl(self):
528 if os.name != "nt":
529 return
530 self.assert_(hasattr(socket.socket, 'ioctl'))
531 self.assert_(hasattr(socket, 'SIO_RCVALL'))
532 self.assert_(hasattr(socket, 'RCVALL_ON'))
533 self.assert_(hasattr(socket, 'RCVALL_OFF'))
534
535
Guido van Rossum24e4af82002-06-12 19:18:08 +0000536class BasicTCPTest(SocketConnectedTest):
537
538 def __init__(self, methodName='runTest'):
539 SocketConnectedTest.__init__(self, methodName=methodName)
540
541 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000542 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000543 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000544 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000545
546 def _testRecv(self):
547 self.serv_conn.send(MSG)
548
549 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000550 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000551 seg1 = self.cli_conn.recv(len(MSG) - 3)
552 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000553 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000554 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000555
556 def _testOverFlowRecv(self):
557 self.serv_conn.send(MSG)
558
559 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000560 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000561 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000562 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000563
564 def _testRecvFrom(self):
565 self.serv_conn.send(MSG)
566
567 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000568 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000569 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
570 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000571 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000572 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000573
574 def _testOverFlowRecvFrom(self):
575 self.serv_conn.send(MSG)
576
577 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000578 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000579 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000580 while 1:
581 read = self.cli_conn.recv(1024)
582 if not read:
583 break
Guido van Rossume531e292002-08-08 20:28:34 +0000584 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000585 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000586
587 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000588 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000589 self.serv_conn.sendall(big_chunk)
590
591 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000592 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000593 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000594 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000595 fd = self.cli_conn.fileno()
596 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
597 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000598 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000599
600 def _testFromFd(self):
601 self.serv_conn.send(MSG)
602
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000603 def testDup(self):
604 # Testing dup()
605 sock = self.cli_conn.dup()
606 msg = sock.recv(1024)
607 self.assertEqual(msg, MSG)
608
609 def _testDup(self):
610 self.serv_conn.send(MSG)
611
Guido van Rossum24e4af82002-06-12 19:18:08 +0000612 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000613 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000614 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000615 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000616
617 def _testShutdown(self):
618 self.serv_conn.send(MSG)
619 self.serv_conn.shutdown(2)
620
621class BasicUDPTest(ThreadedUDPSocketTest):
622
623 def __init__(self, methodName='runTest'):
624 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
625
626 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000627 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000628 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000629 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000630
631 def _testSendtoAndRecv(self):
632 self.cli.sendto(MSG, 0, (HOST, PORT))
633
Guido van Rossum1c938012002-06-12 21:17:20 +0000634 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000635 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000636 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000637 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000638
Guido van Rossum1c938012002-06-12 21:17:20 +0000639 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000640 self.cli.sendto(MSG, 0, (HOST, PORT))
641
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 def testRecvFromNegative(self):
643 # Negative lengths passed to recvfrom should give ValueError.
644 self.assertRaises(ValueError, self.serv.recvfrom, -1)
645
646 def _testRecvFromNegative(self):
647 self.cli.sendto(MSG, 0, (HOST, PORT))
648
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649class TCPCloserTest(ThreadedTCPSocketTest):
650
651 def testClose(self):
652 conn, addr = self.serv.accept()
653 conn.close()
654
655 sd = self.cli
656 read, write, err = select.select([sd], [], [], 1.0)
657 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000658 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000660 # Calling close() many times should be safe.
661 conn.close()
662 conn.close()
663
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000664 def _testClose(self):
665 self.cli.connect((HOST, PORT))
666 time.sleep(1.0)
667
Dave Cole331708b2004-08-09 04:51:41 +0000668class BasicSocketPairTest(SocketPairTest):
669
670 def __init__(self, methodName='runTest'):
671 SocketPairTest.__init__(self, methodName=methodName)
672
673 def testRecv(self):
674 msg = self.serv.recv(1024)
675 self.assertEqual(msg, MSG)
676
677 def _testRecv(self):
678 self.cli.send(MSG)
679
680 def testSend(self):
681 self.serv.send(MSG)
682
683 def _testSend(self):
684 msg = self.cli.recv(1024)
685 self.assertEqual(msg, MSG)
686
Guido van Rossum24e4af82002-06-12 19:18:08 +0000687class NonBlockingTCPTests(ThreadedTCPSocketTest):
688
689 def __init__(self, methodName='runTest'):
690 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
691
692 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000693 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000694 self.serv.setblocking(0)
695 start = time.time()
696 try:
697 self.serv.accept()
698 except socket.error:
699 pass
700 end = time.time()
701 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
702
703 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000704 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000705
Guido van Rossum24e4af82002-06-12 19:18:08 +0000706 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000707 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000708 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000709 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710 conn, addr = self.serv.accept()
711 except socket.error:
712 pass
713 else:
714 self.fail("Error trying to do non-blocking accept.")
715 read, write, err = select.select([self.serv], [], [])
716 if self.serv in read:
717 conn, addr = self.serv.accept()
718 else:
719 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000720
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000722 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000723 self.cli.connect((HOST, PORT))
724
725 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000726 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000727 conn, addr = self.serv.accept()
728
729 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000730 self.cli.settimeout(10)
731 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732
733 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000734 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000735 conn, addr = self.serv.accept()
736 conn.setblocking(0)
737 try:
738 msg = conn.recv(len(MSG))
739 except socket.error:
740 pass
741 else:
742 self.fail("Error trying to do non-blocking recv.")
743 read, write, err = select.select([conn], [], [])
744 if conn in read:
745 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000746 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000747 else:
748 self.fail("Error during select call to non-blocking socket.")
749
750 def _testRecv(self):
751 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000752 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000753 self.cli.send(MSG)
754
755class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000756 """Unit tests for the object returned by socket.makefile()
757
758 self.serv_file is the io object returned by makefile() on
759 the client connection. You can read from this file to
760 get output from the server.
761
762 self.cli_file is the io object returned by makefile() on the
763 server connection. You can write to this file to send output
764 to the client.
765 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000766
Guido van Rossume9f66142002-08-07 15:46:19 +0000767 bufsize = -1 # Use default buffer size
768
Guido van Rossum24e4af82002-06-12 19:18:08 +0000769 def __init__(self, methodName='runTest'):
770 SocketConnectedTest.__init__(self, methodName=methodName)
771
772 def setUp(self):
773 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000774 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000775
776 def tearDown(self):
777 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000778 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000779 self.serv_file = None
780 SocketConnectedTest.tearDown(self)
781
782 def clientSetUp(self):
783 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000784 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000785
786 def clientTearDown(self):
787 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000788 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000789 self.cli_file = None
790 SocketConnectedTest.clientTearDown(self)
791
792 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000793 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000794 first_seg = self.serv_file.read(len(MSG)-3)
795 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000796 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000797 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000798
799 def _testSmallRead(self):
800 self.cli_file.write(MSG)
801 self.cli_file.flush()
802
Guido van Rossum8c943832002-08-08 01:00:28 +0000803 def testFullRead(self):
804 # read until EOF
805 msg = self.serv_file.read()
806 self.assertEqual(msg, MSG)
807
808 def _testFullRead(self):
809 self.cli_file.write(MSG)
810 self.cli_file.close()
811
Guido van Rossum24e4af82002-06-12 19:18:08 +0000812 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000813 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000814 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000815 while 1:
816 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000817 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000818 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000819 buf += char
820 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000821
822 def _testUnbufferedRead(self):
823 self.cli_file.write(MSG)
824 self.cli_file.flush()
825
826 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000827 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000828 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000829 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000830
831 def _testReadline(self):
832 self.cli_file.write(MSG)
833 self.cli_file.flush()
834
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000835 def testCloseAfterMakefile(self):
836 # The file returned by makefile should keep the socket open.
837 self.cli_conn.close()
838 # read until EOF
839 msg = self.serv_file.read()
840 self.assertEqual(msg, MSG)
841
842 def _testCloseAfterMakefile(self):
843 self.cli_file.write(MSG)
844 self.cli_file.flush()
845
846 def testMakefileAfterMakefileClose(self):
847 self.serv_file.close()
848 msg = self.cli_conn.recv(len(MSG))
849 self.assertEqual(msg, MSG)
850
851 def _testMakefileAfterMakefileClose(self):
852 self.cli_file.write(MSG)
853 self.cli_file.flush()
854
Tim Peters116d83c2004-03-28 02:20:45 +0000855 def testClosedAttr(self):
856 self.assert_(not self.serv_file.closed)
857
858 def _testClosedAttr(self):
859 self.assert_(not self.cli_file.closed)
860
Guido van Rossume9f66142002-08-07 15:46:19 +0000861class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
862
863 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000864
Guido van Rossume9f66142002-08-07 15:46:19 +0000865 In this case (and in this case only), it should be possible to
866 create a file object, read a line from it, create another file
867 object, read another line from it, without loss of data in the
868 first file object's buffer. Note that httplib relies on this
869 when reading multiple requests from the same socket."""
870
871 bufsize = 0 # Use unbuffered mode
872
873 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000874 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000875 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000876 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000877 self.serv_file = self.cli_conn.makefile('rb', 0)
878 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000879 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000880
881 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000882 self.cli_file.write(b"A. " + MSG)
883 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000884 self.cli_file.flush()
885
Guido van Rossum8c943832002-08-08 01:00:28 +0000886class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
887
888 bufsize = 1 # Default-buffered for reading; line-buffered for writing
889
890
891class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
892
893 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000894
Thomas Woutersb2137042007-02-01 18:02:27 +0000895
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896class NetworkConnectionTest(object):
897 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000898
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 def clientSetUp(self):
900 self.cli = socket.create_connection((HOST, PORT))
901 self.serv_conn = self.cli
902
903class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
904 """Tests that NetworkConnection does not break existing TCP functionality.
905 """
906
907class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000908
Guido van Rossumd8faa362007-04-27 19:54:29 +0000909 def testWithoutServer(self):
910 self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
911
912class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
913
914 def __init__(self, methodName='runTest'):
915 SocketTCPTest.__init__(self, methodName=methodName)
916 ThreadableTest.__init__(self)
917
918 def clientSetUp(self):
919 pass
920
921 def clientTearDown(self):
922 self.cli.close()
923 self.cli = None
924 ThreadableTest.clientTearDown(self)
925
926 def _justAccept(self):
927 conn, addr = self.serv.accept()
928
929 testFamily = _justAccept
930 def _testFamily(self):
931 self.cli = socket.create_connection((HOST, PORT), timeout=30)
932 self.assertEqual(self.cli.family, 2)
933
934 testTimeoutDefault = _justAccept
935 def _testTimeoutDefault(self):
936 self.cli = socket.create_connection((HOST, PORT))
937 self.assertTrue(self.cli.gettimeout() is None)
938
939 testTimeoutValueNamed = _justAccept
940 def _testTimeoutValueNamed(self):
941 self.cli = socket.create_connection((HOST, PORT), timeout=30)
942 self.assertEqual(self.cli.gettimeout(), 30)
943
944 testTimeoutValueNonamed = _justAccept
945 def _testTimeoutValueNonamed(self):
946 self.cli = socket.create_connection((HOST, PORT), 30)
947 self.assertEqual(self.cli.gettimeout(), 30)
948
949 testTimeoutNone = _justAccept
950 def _testTimeoutNone(self):
951 previous = socket.getdefaulttimeout()
952 socket.setdefaulttimeout(30)
953 try:
954 self.cli = socket.create_connection((HOST, PORT), timeout=None)
955 finally:
956 socket.setdefaulttimeout(previous)
957 self.assertEqual(self.cli.gettimeout(), 30)
958
959
960class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
961
962 def __init__(self, methodName='runTest'):
963 SocketTCPTest.__init__(self, methodName=methodName)
964 ThreadableTest.__init__(self)
965
966 def clientSetUp(self):
967 pass
968
969 def clientTearDown(self):
970 self.cli.close()
971 self.cli = None
972 ThreadableTest.clientTearDown(self)
973
974 def testInsideTimeout(self):
975 conn, addr = self.serv.accept()
976 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000977 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978 testOutsideTimeout = testInsideTimeout
979
980 def _testInsideTimeout(self):
981 self.cli = sock = socket.create_connection((HOST, PORT))
982 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000983 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984
985 def _testOutsideTimeout(self):
986 self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
987 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
988
989
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000990class TCPTimeoutTest(SocketTCPTest):
991
992 def testTCPTimeout(self):
993 def raise_timeout(*args, **kwargs):
994 self.serv.settimeout(1.0)
995 self.serv.accept()
996 self.failUnlessRaises(socket.timeout, raise_timeout,
997 "Error generating a timeout exception (TCP)")
998
999 def testTimeoutZero(self):
1000 ok = False
1001 try:
1002 self.serv.settimeout(0.0)
1003 foo = self.serv.accept()
1004 except socket.timeout:
1005 self.fail("caught timeout instead of error (TCP)")
1006 except socket.error:
1007 ok = True
1008 except:
1009 self.fail("caught unexpected exception (TCP)")
1010 if not ok:
1011 self.fail("accept() returned success when we did not expect it")
1012
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013 def testInterruptedTimeout(self):
1014 # XXX I don't know how to do this test on MSWindows or any other
1015 # plaform that doesn't support signal.alarm() or os.kill(), though
1016 # the bug should have existed on all platforms.
1017 if not hasattr(signal, "alarm"):
1018 return # can only test on *nix
1019 self.serv.settimeout(5.0) # must be longer than alarm
1020 class Alarm(Exception):
1021 pass
1022 def alarm_handler(signal, frame):
1023 raise Alarm
1024 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1025 try:
1026 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1027 try:
1028 foo = self.serv.accept()
1029 except socket.timeout:
1030 self.fail("caught timeout instead of Alarm")
1031 except Alarm:
1032 pass
1033 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001034 self.fail("caught other exception instead of Alarm:"
1035 " %s(%s):\n%s" %
1036 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001037 else:
1038 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001039 finally:
1040 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001041 except Alarm:
1042 self.fail("got Alarm in wrong place")
1043 finally:
1044 # no alarm can be pending. Safe to restore old handler.
1045 signal.signal(signal.SIGALRM, old_alarm)
1046
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001047class UDPTimeoutTest(SocketTCPTest):
1048
1049 def testUDPTimeout(self):
1050 def raise_timeout(*args, **kwargs):
1051 self.serv.settimeout(1.0)
1052 self.serv.recv(1024)
1053 self.failUnlessRaises(socket.timeout, raise_timeout,
1054 "Error generating a timeout exception (UDP)")
1055
1056 def testTimeoutZero(self):
1057 ok = False
1058 try:
1059 self.serv.settimeout(0.0)
1060 foo = self.serv.recv(1024)
1061 except socket.timeout:
1062 self.fail("caught timeout instead of error (UDP)")
1063 except socket.error:
1064 ok = True
1065 except:
1066 self.fail("caught unexpected exception (UDP)")
1067 if not ok:
1068 self.fail("recv() returned success when we did not expect it")
1069
1070class TestExceptions(unittest.TestCase):
1071
1072 def testExceptionTree(self):
1073 self.assert_(issubclass(socket.error, Exception))
1074 self.assert_(issubclass(socket.herror, socket.error))
1075 self.assert_(issubclass(socket.gaierror, socket.error))
1076 self.assert_(issubclass(socket.timeout, socket.error))
1077
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001078class TestLinuxAbstractNamespace(unittest.TestCase):
1079
1080 UNIX_PATH_MAX = 108
1081
1082 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001083 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001084 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1085 s1.bind(address)
1086 s1.listen(1)
1087 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1088 s2.connect(s1.getsockname())
1089 s1.accept()
1090 self.assertEqual(s1.getsockname(), address)
1091 self.assertEqual(s2.getpeername(), address)
1092
1093 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001094 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001095 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1096 s.bind(address)
1097 self.assertEqual(s.getsockname(), address)
1098
1099 def testNameOverflow(self):
1100 address = "\x00" + "h" * self.UNIX_PATH_MAX
1101 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1102 self.assertRaises(socket.error, s.bind, address)
1103
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001104
Thomas Wouters477c8d52006-05-27 19:21:47 +00001105class BufferIOTest(SocketConnectedTest):
1106 """
1107 Test the buffer versions of socket.recv() and socket.send().
1108 """
1109 def __init__(self, methodName='runTest'):
1110 SocketConnectedTest.__init__(self, methodName=methodName)
1111
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001112 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001113 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001114 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001116 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 self.assertEqual(msg, MSG)
1118
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001119 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001120 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 self.serv_conn.send(buf)
1122
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001123 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001124 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001125 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001127 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128 self.assertEqual(msg, MSG)
1129
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001130 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001131 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001132 self.serv_conn.send(buf)
1133
Christian Heimes043d6f62008-01-07 17:19:16 +00001134
1135TIPC_STYPE = 2000
1136TIPC_LOWER = 200
1137TIPC_UPPER = 210
1138
1139def isTipcAvailable():
1140 """Check if the TIPC module is loaded
1141
1142 The TIPC module is not loaded automatically on Ubuntu and probably
1143 other Linux distros.
1144 """
1145 if not hasattr(socket, "AF_TIPC"):
1146 return False
1147 if not os.path.isfile("/proc/modules"):
1148 return False
1149 with open("/proc/modules") as f:
1150 for line in f:
1151 if line.startswith("tipc "):
1152 return True
Christian Heimes2380ac72008-01-09 00:17:24 +00001153 if test_support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001154 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1155 return False
1156
1157class TIPCTest (unittest.TestCase):
1158 def testRDM(self):
1159 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1160 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1161
1162 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1163 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1164 TIPC_LOWER, TIPC_UPPER)
1165 srv.bind(srvaddr)
1166
1167 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1168 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1169 cli.sendto(MSG, sendaddr)
1170
1171 msg, recvaddr = srv.recvfrom(1024)
1172
1173 self.assertEqual(cli.getsockname(), recvaddr)
1174 self.assertEqual(msg, MSG)
1175
1176
1177class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1178 def __init__(self, methodName = 'runTest'):
1179 unittest.TestCase.__init__(self, methodName = methodName)
1180 ThreadableTest.__init__(self)
1181
1182 def setUp(self):
1183 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1184 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1185 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1186 TIPC_LOWER, TIPC_UPPER)
1187 self.srv.bind(srvaddr)
1188 self.srv.listen(5)
1189 self.serverExplicitReady()
1190 self.conn, self.connaddr = self.srv.accept()
1191
1192 def clientSetUp(self):
1193 # The is a hittable race between serverExplicitReady() and the
1194 # accept() call; sleep a little while to avoid it, otherwise
1195 # we could get an exception
1196 time.sleep(0.1)
1197 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1198 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1199 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1200 self.cli.connect(addr)
1201 self.cliaddr = self.cli.getsockname()
1202
1203 def testStream(self):
1204 msg = self.conn.recv(1024)
1205 self.assertEqual(msg, MSG)
1206 self.assertEqual(self.cliaddr, self.connaddr)
1207
1208 def _testStream(self):
1209 self.cli.send(MSG)
1210 self.cli.close()
1211
1212
Guido van Rossumb995eb72002-07-31 16:08:40 +00001213def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001214 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001216 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001217 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001218
1219 tests.extend([
1220 NonBlockingTCPTests,
1221 FileObjectClassTestCase,
1222 UnbufferedFileObjectClassTestCase,
1223 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001224 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001225 NetworkConnectionNoServer,
1226 NetworkConnectionAttributesTest,
1227 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001228 ])
Dave Cole331708b2004-08-09 04:51:41 +00001229 if hasattr(socket, "socketpair"):
1230 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001231 if sys.platform == 'linux2':
1232 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001233 if isTipcAvailable():
1234 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001235 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001236
1237 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001238 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001239 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001240
1241if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001242 test_main()