blob: 8c5cf93e77ae19f50c5b293f41408219bf863e3d [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
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import thread, threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000010import time
11import traceback
Guido van Rossum24e4af82002-06-12 19:18:08 +000012import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000013import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000014import os
15import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000016from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000018
Christian Heimes5e696852008-04-09 08:37:03 +000019HOST = test_support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000020MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000021
Guido van Rossum24e4af82002-06-12 19:18:08 +000022class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000023
Guido van Rossum24e4af82002-06-12 19:18:08 +000024 def setUp(self):
25 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +000026 self.port = test_support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000027 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000028
Guido van Rossum24e4af82002-06-12 19:18:08 +000029 def tearDown(self):
30 self.serv.close()
31 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000032
Guido van Rossum24e4af82002-06-12 19:18:08 +000033class SocketUDPTest(unittest.TestCase):
34
35 def setUp(self):
36 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Christian Heimes5e696852008-04-09 08:37:03 +000037 self.port = test_support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000038
39 def tearDown(self):
40 self.serv.close()
41 self.serv = None
42
43class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000044 """Threadable Test class
45
46 The ThreadableTest class makes it easy to create a threaded
47 client/server pair from an existing unit test. To create a
48 new threaded class from an existing unit test, use multiple
49 inheritance:
50
51 class NewClass (OldClass, ThreadableTest):
52 pass
53
54 This class defines two new fixture functions with obvious
55 purposes for overriding:
56
57 clientSetUp ()
58 clientTearDown ()
59
60 Any new test functions within the class must then define
61 tests in pairs, where the test name is preceeded with a
62 '_' to indicate the client portion of the test. Ex:
63
64 def testFoo(self):
65 # Server portion
66
67 def _testFoo(self):
68 # Client portion
69
70 Any exceptions raised by the clients during their tests
71 are caught and transferred to the main thread to alert
72 the testing framework.
73
74 Note, the server setup function cannot call any blocking
75 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000076 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000077 the blocking call (such as in setting up a client/server
78 connection and performing the accept() in setUp().
79 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000080
81 def __init__(self):
82 # Swap the true setup function
83 self.__setUp = self.setUp
84 self.__tearDown = self.tearDown
85 self.setUp = self._setUp
86 self.tearDown = self._tearDown
87
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000088 def serverExplicitReady(self):
89 """This method allows the server to explicitly indicate that
90 it wants the client thread to proceed. This is useful if the
91 server is about to execute a blocking routine that is
92 dependent upon the client thread during its setup routine."""
93 self.server_ready.set()
94
Guido van Rossum24e4af82002-06-12 19:18:08 +000095 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000096 self.server_ready = threading.Event()
97 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000098 self.done = threading.Event()
99 self.queue = Queue.Queue(1)
100
101 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000102 methodname = self.id()
103 i = methodname.rfind('.')
104 methodname = methodname[i+1:]
105 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000106 self.client_thread = thread.start_new_thread(
107 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000108
109 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000110 if not self.server_ready.isSet():
111 self.server_ready.set()
112 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000113
114 def _tearDown(self):
115 self.__tearDown()
116 self.done.wait()
117
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000118 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000119 msg = self.queue.get()
120 self.fail(msg)
121
122 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000123 self.server_ready.wait()
124 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000125 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000126 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000127 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000128 try:
129 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000130 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000131 self.queue.put(strerror)
132 self.clientTearDown()
133
134 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000135 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000136
137 def clientTearDown(self):
138 self.done.set()
139 thread.exit()
140
141class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
142
143 def __init__(self, methodName='runTest'):
144 SocketTCPTest.__init__(self, methodName=methodName)
145 ThreadableTest.__init__(self)
146
147 def clientSetUp(self):
148 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
149
150 def clientTearDown(self):
151 self.cli.close()
152 self.cli = None
153 ThreadableTest.clientTearDown(self)
154
155class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
156
157 def __init__(self, methodName='runTest'):
158 SocketUDPTest.__init__(self, methodName=methodName)
159 ThreadableTest.__init__(self)
160
161 def clientSetUp(self):
162 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
163
164class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000165 """Socket tests for client-server connection.
166
167 self.cli_conn is a client socket connected to the server. The
168 setUp() method guarantees that it is connected to the server.
169 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000170
171 def __init__(self, methodName='runTest'):
172 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
173
174 def setUp(self):
175 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000176 # Indicate explicitly we're ready for the client thread to
177 # proceed and then perform the blocking call to accept
178 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000179 conn, addr = self.serv.accept()
180 self.cli_conn = conn
181
182 def tearDown(self):
183 self.cli_conn.close()
184 self.cli_conn = None
185 ThreadedTCPSocketTest.tearDown(self)
186
187 def clientSetUp(self):
188 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000189 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000190 self.serv_conn = self.cli
191
192 def clientTearDown(self):
193 self.serv_conn.close()
194 self.serv_conn = None
195 ThreadedTCPSocketTest.clientTearDown(self)
196
Dave Cole331708b2004-08-09 04:51:41 +0000197class SocketPairTest(unittest.TestCase, ThreadableTest):
198
199 def __init__(self, methodName='runTest'):
200 unittest.TestCase.__init__(self, methodName=methodName)
201 ThreadableTest.__init__(self)
202
203 def setUp(self):
204 self.serv, self.cli = socket.socketpair()
205
206 def tearDown(self):
207 self.serv.close()
208 self.serv = None
209
210 def clientSetUp(self):
211 pass
212
213 def clientTearDown(self):
214 self.cli.close()
215 self.cli = None
216 ThreadableTest.clientTearDown(self)
217
Tim Peters494aaee2004-08-09 18:54:11 +0000218
Guido van Rossum24e4af82002-06-12 19:18:08 +0000219#######################################################################
220## Begin Tests
221
222class GeneralModuleTests(unittest.TestCase):
223
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000224 def test_repr(self):
225 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
226 self.assert_(repr(s).startswith("<socket.socket object"))
227
Raymond Hettinger027bb632004-05-31 03:09:25 +0000228 def test_weakref(self):
229 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
230 p = proxy(s)
231 self.assertEqual(p.fileno(), s.fileno())
232 s.close()
233 s = None
234 try:
235 p.fileno()
236 except ReferenceError:
237 pass
238 else:
239 self.fail('Socket proxy still exists')
240
Guido van Rossum24e4af82002-06-12 19:18:08 +0000241 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000242 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000243 def raise_error(*args, **kwargs):
244 raise socket.error
245 def raise_herror(*args, **kwargs):
246 raise socket.herror
247 def raise_gaierror(*args, **kwargs):
248 raise socket.gaierror
249 self.failUnlessRaises(socket.error, raise_error,
250 "Error raising socket exception.")
251 self.failUnlessRaises(socket.error, raise_herror,
252 "Error raising socket exception.")
253 self.failUnlessRaises(socket.error, raise_gaierror,
254 "Error raising socket exception.")
255
256 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000257 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000258 socket.AF_INET
259 socket.SOCK_STREAM
260 socket.SOCK_DGRAM
261 socket.SOCK_RAW
262 socket.SOCK_RDM
263 socket.SOCK_SEQPACKET
264 socket.SOL_SOCKET
265 socket.SO_REUSEADDR
266
Guido van Rossum654c11e2002-06-13 20:24:17 +0000267 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000268 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000269 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000270 try:
271 ip = socket.gethostbyname(hostname)
272 except socket.error:
273 # Probably name lookup wasn't set up right; skip this test
274 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000275 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000276 try:
277 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
278 except socket.error:
279 # Probably a similar problem as above; skip this test
280 return
Brett Cannon01668a12005-03-11 00:04:17 +0000281 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000282 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000283 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000285
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000286 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000287 # Testing reference count for getnameinfo
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000288 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000289 try:
290 # On some versions, this loses a reference
291 orig = sys.getrefcount(__name__)
292 socket.getnameinfo(__name__,0)
293 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000294 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000295 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000296
Guido van Rossum24e4af82002-06-12 19:18:08 +0000297 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000298 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000299 try:
300 # On some versions, this crashes the interpreter.
301 socket.getnameinfo(('x', 0, 0, 0), 0)
302 except socket.error:
303 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000304
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000305 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000306 # This just checks that htons etc. are their own inverse,
307 # when looking at the lower 16 or 32 bits.
308 sizes = {socket.htonl: 32, socket.ntohl: 32,
309 socket.htons: 16, socket.ntohs: 16}
310 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000311 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000312 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
313 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000314
Guido van Rossuma2627af2002-09-14 00:58:46 +0000315 swapped = func(mask)
316 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000317 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000318
Guido van Rossum018919a2007-01-15 00:07:32 +0000319 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000320 good_values = [ 1, 2, 3, 1, 2, 3 ]
321 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000322 for k in good_values:
323 socket.ntohl(k)
324 socket.ntohs(k)
325 socket.htonl(k)
326 socket.htons(k)
327 for k in bad_values:
328 self.assertRaises(OverflowError, socket.ntohl, k)
329 self.assertRaises(OverflowError, socket.ntohs, k)
330 self.assertRaises(OverflowError, socket.htonl, k)
331 self.assertRaises(OverflowError, socket.htons, k)
332
Barry Warsaw11b91a02004-06-28 00:50:43 +0000333 def testGetServBy(self):
334 eq = self.assertEqual
335 # Find one service that exists, then check all the related interfaces.
336 # I've ordered this by protocols that have both a tcp and udp
337 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000338 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000339 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000340 # avoid the 'echo' service on this platform, as there is an
341 # assumption breaking non-standard port/protocol entry
342 services = ('daytime', 'qotd', 'domain')
343 else:
344 services = ('echo', 'daytime', 'domain')
345 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000346 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000347 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000348 break
349 except socket.error:
350 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000351 else:
352 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000353 # Try same call with optional protocol omitted
354 port2 = socket.getservbyname(service)
355 eq(port, port2)
356 # Try udp, but don't barf it it doesn't exist
357 try:
358 udpport = socket.getservbyname(service, 'udp')
359 except socket.error:
360 udpport = None
361 else:
362 eq(udpport, port)
363 # Now make sure the lookup by port returns the same service name
364 eq(socket.getservbyport(port2), service)
365 eq(socket.getservbyport(port, 'tcp'), service)
366 if udpport is not None:
367 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000368
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000369 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000370 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000371 # The default timeout should initially be None
372 self.assertEqual(socket.getdefaulttimeout(), None)
373 s = socket.socket()
374 self.assertEqual(s.gettimeout(), None)
375 s.close()
376
377 # Set the default timeout to 10, and see if it propagates
378 socket.setdefaulttimeout(10)
379 self.assertEqual(socket.getdefaulttimeout(), 10)
380 s = socket.socket()
381 self.assertEqual(s.gettimeout(), 10)
382 s.close()
383
384 # Reset the default timeout to None, and see if it propagates
385 socket.setdefaulttimeout(None)
386 self.assertEqual(socket.getdefaulttimeout(), None)
387 s = socket.socket()
388 self.assertEqual(s.gettimeout(), None)
389 s.close()
390
391 # Check that setting it to an invalid value raises ValueError
392 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
393
394 # Check that setting it to an invalid type raises TypeError
395 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
396
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000397 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000398 if not hasattr(socket, 'inet_pton'):
399 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000400 from socket import inet_aton as f, inet_pton, AF_INET
401 g = lambda a: inet_pton(AF_INET, a)
402
Guido van Rossumb5b22702007-05-18 18:55:53 +0000403 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
404 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
405 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
406 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
407 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000408
Guido van Rossumb5b22702007-05-18 18:55:53 +0000409 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
410 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
411 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
412 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000413
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000414 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000415 if not hasattr(socket, 'inet_pton'):
416 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000417 try:
418 from socket import inet_pton, AF_INET6, has_ipv6
419 if not has_ipv6:
420 return
421 except ImportError:
422 return
423 f = lambda a: inet_pton(AF_INET6, a)
424
Guido van Rossum540d9872007-08-17 03:51:09 +0000425 self.assertEquals(b'\x00' * 16, f('::'))
426 self.assertEquals(b'\x00' * 16, f('0::0'))
427 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000428 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000429 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 +0000430 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
431 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000432
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000433 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000434 if not hasattr(socket, 'inet_ntop'):
435 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000436 from socket import inet_ntoa as f, inet_ntop, AF_INET
437 g = lambda a: inet_ntop(AF_INET, a)
438
Guido van Rossumb5b22702007-05-18 18:55:53 +0000439 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
440 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
441 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
442 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000443
Guido van Rossumb5b22702007-05-18 18:55:53 +0000444 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
445 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
446 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000447
448 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000449 if not hasattr(socket, 'inet_ntop'):
450 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000451 try:
452 from socket import inet_ntop, AF_INET6, has_ipv6
453 if not has_ipv6:
454 return
455 except ImportError:
456 return
457 f = lambda a: inet_ntop(AF_INET6, a)
458
Guido van Rossum540d9872007-08-17 03:51:09 +0000459 self.assertEquals('::', f(b'\x00' * 16))
460 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000461 self.assertEquals(
462 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000463 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 +0000464 )
465
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000466 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000467
Guido van Rossum24e4af82002-06-12 19:18:08 +0000468 def testSockName(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000469 # Testing getsockname(). Use a temporary socket to elicit an unused
470 # ephemeral port that we can use later in the test.
471 tempsock = socket.socket()
472 tempsock.bind(("0.0.0.0", 0))
473 (host, port) = tempsock.getsockname()
474 tempsock.close()
475 del tempsock
476
Guido van Rossum24e4af82002-06-12 19:18:08 +0000477 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000478 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000479 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
481 # it reasonable to get the host's addr in addition to 0.0.0.0.
482 # At least for eCos. This is required for the S/390 to pass.
483 my_ip_addr = socket.gethostbyname(socket.gethostname())
484 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000485 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000486
487 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000488 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000489 # We know a socket should start without reuse==0
490 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
491 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000492 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000493
494 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000495 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000496 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
497 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
498 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000499 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000500
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000501 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000502 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000503 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
504 sock.settimeout(1)
505 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000506 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000507
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000508 def testNewAttributes(self):
509 # testing .family, .type and .protocol
510 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
511 self.assertEqual(sock.family, socket.AF_INET)
512 self.assertEqual(sock.type, socket.SOCK_STREAM)
513 self.assertEqual(sock.proto, 0)
514 sock.close()
515
Christian Heimesfaf2f632008-01-06 16:59:19 +0000516 def test_sock_ioctl(self):
517 if os.name != "nt":
518 return
519 self.assert_(hasattr(socket.socket, 'ioctl'))
520 self.assert_(hasattr(socket, 'SIO_RCVALL'))
521 self.assert_(hasattr(socket, 'RCVALL_ON'))
522 self.assert_(hasattr(socket, 'RCVALL_OFF'))
523
524
Guido van Rossum24e4af82002-06-12 19:18:08 +0000525class BasicTCPTest(SocketConnectedTest):
526
527 def __init__(self, methodName='runTest'):
528 SocketConnectedTest.__init__(self, methodName=methodName)
529
530 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000531 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000532 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000533 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000534
535 def _testRecv(self):
536 self.serv_conn.send(MSG)
537
538 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000539 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000540 seg1 = self.cli_conn.recv(len(MSG) - 3)
541 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000542 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000543 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000544
545 def _testOverFlowRecv(self):
546 self.serv_conn.send(MSG)
547
548 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000549 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000550 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000551 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000552
553 def _testRecvFrom(self):
554 self.serv_conn.send(MSG)
555
556 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000557 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000558 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
559 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000560 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000561 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000562
563 def _testOverFlowRecvFrom(self):
564 self.serv_conn.send(MSG)
565
566 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000567 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000568 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000569 while 1:
570 read = self.cli_conn.recv(1024)
571 if not read:
572 break
Guido van Rossume531e292002-08-08 20:28:34 +0000573 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000574 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000575
576 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000577 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000578 self.serv_conn.sendall(big_chunk)
579
580 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000581 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000582 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000583 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000584 fd = self.cli_conn.fileno()
585 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
586 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000587 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000588
589 def _testFromFd(self):
590 self.serv_conn.send(MSG)
591
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000592 def testDup(self):
593 # Testing dup()
594 sock = self.cli_conn.dup()
595 msg = sock.recv(1024)
596 self.assertEqual(msg, MSG)
597
598 def _testDup(self):
599 self.serv_conn.send(MSG)
600
Guido van Rossum24e4af82002-06-12 19:18:08 +0000601 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000602 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000603 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000604 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000605
606 def _testShutdown(self):
607 self.serv_conn.send(MSG)
608 self.serv_conn.shutdown(2)
609
610class BasicUDPTest(ThreadedUDPSocketTest):
611
612 def __init__(self, methodName='runTest'):
613 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
614
615 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000616 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000617 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000618 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000619
620 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000621 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000622
Guido van Rossum1c938012002-06-12 21:17:20 +0000623 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000624 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000625 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000626 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000627
Guido van Rossum1c938012002-06-12 21:17:20 +0000628 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000629 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000630
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 def testRecvFromNegative(self):
632 # Negative lengths passed to recvfrom should give ValueError.
633 self.assertRaises(ValueError, self.serv.recvfrom, -1)
634
635 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000636 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638class TCPCloserTest(ThreadedTCPSocketTest):
639
640 def testClose(self):
641 conn, addr = self.serv.accept()
642 conn.close()
643
644 sd = self.cli
645 read, write, err = select.select([sd], [], [], 1.0)
646 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000647 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000649 # Calling close() many times should be safe.
650 conn.close()
651 conn.close()
652
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000654 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655 time.sleep(1.0)
656
Dave Cole331708b2004-08-09 04:51:41 +0000657class BasicSocketPairTest(SocketPairTest):
658
659 def __init__(self, methodName='runTest'):
660 SocketPairTest.__init__(self, methodName=methodName)
661
662 def testRecv(self):
663 msg = self.serv.recv(1024)
664 self.assertEqual(msg, MSG)
665
666 def _testRecv(self):
667 self.cli.send(MSG)
668
669 def testSend(self):
670 self.serv.send(MSG)
671
672 def _testSend(self):
673 msg = self.cli.recv(1024)
674 self.assertEqual(msg, MSG)
675
Guido van Rossum24e4af82002-06-12 19:18:08 +0000676class NonBlockingTCPTests(ThreadedTCPSocketTest):
677
678 def __init__(self, methodName='runTest'):
679 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
680
681 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000682 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000683 self.serv.setblocking(0)
684 start = time.time()
685 try:
686 self.serv.accept()
687 except socket.error:
688 pass
689 end = time.time()
690 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
691
692 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000693 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000694
Guido van Rossum24e4af82002-06-12 19:18:08 +0000695 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000696 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000697 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000698 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000699 conn, addr = self.serv.accept()
700 except socket.error:
701 pass
702 else:
703 self.fail("Error trying to do non-blocking accept.")
704 read, write, err = select.select([self.serv], [], [])
705 if self.serv in read:
706 conn, addr = self.serv.accept()
707 else:
708 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000709
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000711 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000712 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713
714 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000715 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000716 conn, addr = self.serv.accept()
717
718 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000719 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000720 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000721
722 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000723 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000724 conn, addr = self.serv.accept()
725 conn.setblocking(0)
726 try:
727 msg = conn.recv(len(MSG))
728 except socket.error:
729 pass
730 else:
731 self.fail("Error trying to do non-blocking recv.")
732 read, write, err = select.select([conn], [], [])
733 if conn in read:
734 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000735 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000736 else:
737 self.fail("Error during select call to non-blocking socket.")
738
739 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000740 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000741 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000742 self.cli.send(MSG)
743
744class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000745 """Unit tests for the object returned by socket.makefile()
746
747 self.serv_file is the io object returned by makefile() on
748 the client connection. You can read from this file to
749 get output from the server.
750
751 self.cli_file is the io object returned by makefile() on the
752 server connection. You can write to this file to send output
753 to the client.
754 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755
Guido van Rossume9f66142002-08-07 15:46:19 +0000756 bufsize = -1 # Use default buffer size
757
Guido van Rossum24e4af82002-06-12 19:18:08 +0000758 def __init__(self, methodName='runTest'):
759 SocketConnectedTest.__init__(self, methodName=methodName)
760
761 def setUp(self):
762 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000763 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764
765 def tearDown(self):
766 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000767 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000768 self.serv_file = None
769 SocketConnectedTest.tearDown(self)
770
771 def clientSetUp(self):
772 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000773 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000774
775 def clientTearDown(self):
776 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000777 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000778 self.cli_file = None
779 SocketConnectedTest.clientTearDown(self)
780
781 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000782 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000783 first_seg = self.serv_file.read(len(MSG)-3)
784 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000785 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000786 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000787
788 def _testSmallRead(self):
789 self.cli_file.write(MSG)
790 self.cli_file.flush()
791
Guido van Rossum8c943832002-08-08 01:00:28 +0000792 def testFullRead(self):
793 # read until EOF
794 msg = self.serv_file.read()
795 self.assertEqual(msg, MSG)
796
797 def _testFullRead(self):
798 self.cli_file.write(MSG)
799 self.cli_file.close()
800
Guido van Rossum24e4af82002-06-12 19:18:08 +0000801 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000802 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000803 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000804 while 1:
805 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000806 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000807 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000808 buf += char
809 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000810
811 def _testUnbufferedRead(self):
812 self.cli_file.write(MSG)
813 self.cli_file.flush()
814
815 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000816 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000817 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000818 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000819
820 def _testReadline(self):
821 self.cli_file.write(MSG)
822 self.cli_file.flush()
823
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000824 def testCloseAfterMakefile(self):
825 # The file returned by makefile should keep the socket open.
826 self.cli_conn.close()
827 # read until EOF
828 msg = self.serv_file.read()
829 self.assertEqual(msg, MSG)
830
831 def _testCloseAfterMakefile(self):
832 self.cli_file.write(MSG)
833 self.cli_file.flush()
834
835 def testMakefileAfterMakefileClose(self):
836 self.serv_file.close()
837 msg = self.cli_conn.recv(len(MSG))
838 self.assertEqual(msg, MSG)
839
840 def _testMakefileAfterMakefileClose(self):
841 self.cli_file.write(MSG)
842 self.cli_file.flush()
843
Tim Peters116d83c2004-03-28 02:20:45 +0000844 def testClosedAttr(self):
845 self.assert_(not self.serv_file.closed)
846
847 def _testClosedAttr(self):
848 self.assert_(not self.cli_file.closed)
849
Guido van Rossume9f66142002-08-07 15:46:19 +0000850class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
851
852 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000853
Guido van Rossume9f66142002-08-07 15:46:19 +0000854 In this case (and in this case only), it should be possible to
855 create a file object, read a line from it, create another file
856 object, read another line from it, without loss of data in the
857 first file object's buffer. Note that httplib relies on this
858 when reading multiple requests from the same socket."""
859
860 bufsize = 0 # Use unbuffered mode
861
862 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000863 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000864 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000865 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000866 self.serv_file = self.cli_conn.makefile('rb', 0)
867 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000868 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000869
870 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000871 self.cli_file.write(b"A. " + MSG)
872 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000873 self.cli_file.flush()
874
Guido van Rossum8c943832002-08-08 01:00:28 +0000875class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
876
877 bufsize = 1 # Default-buffered for reading; line-buffered for writing
878
879
880class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
881
882 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000883
Thomas Woutersb2137042007-02-01 18:02:27 +0000884
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885class NetworkConnectionTest(object):
886 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000887
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000889 # We're inherited below by BasicTCPTest2, which also inherits
890 # BasicTCPTest, which defines self.port referenced below.
891 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892 self.serv_conn = self.cli
893
894class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
895 """Tests that NetworkConnection does not break existing TCP functionality.
896 """
897
898class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000899
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900 def testWithoutServer(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000901 port = test_support.find_unused_port()
902 self.failUnlessRaises(
903 socket.error,
904 lambda: socket.create_connection((HOST, port))
905 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000906
907class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
908
909 def __init__(self, methodName='runTest'):
910 SocketTCPTest.__init__(self, methodName=methodName)
911 ThreadableTest.__init__(self)
912
913 def clientSetUp(self):
914 pass
915
916 def clientTearDown(self):
917 self.cli.close()
918 self.cli = None
919 ThreadableTest.clientTearDown(self)
920
921 def _justAccept(self):
922 conn, addr = self.serv.accept()
923
924 testFamily = _justAccept
925 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000926 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927 self.assertEqual(self.cli.family, 2)
928
929 testTimeoutDefault = _justAccept
930 def _testTimeoutDefault(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000931 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000932 self.assertTrue(self.cli.gettimeout() is None)
933
934 testTimeoutValueNamed = _justAccept
935 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000936 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937 self.assertEqual(self.cli.gettimeout(), 30)
938
939 testTimeoutValueNonamed = _justAccept
940 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000941 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 self.assertEqual(self.cli.gettimeout(), 30)
943
944 testTimeoutNone = _justAccept
945 def _testTimeoutNone(self):
946 previous = socket.getdefaulttimeout()
947 socket.setdefaulttimeout(30)
948 try:
Christian Heimes5e696852008-04-09 08:37:03 +0000949 self.cli = socket.create_connection((HOST, self.port), timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 finally:
951 socket.setdefaulttimeout(previous)
952 self.assertEqual(self.cli.gettimeout(), 30)
953
954
955class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
956
957 def __init__(self, methodName='runTest'):
958 SocketTCPTest.__init__(self, methodName=methodName)
959 ThreadableTest.__init__(self)
960
961 def clientSetUp(self):
962 pass
963
964 def clientTearDown(self):
965 self.cli.close()
966 self.cli = None
967 ThreadableTest.clientTearDown(self)
968
969 def testInsideTimeout(self):
970 conn, addr = self.serv.accept()
971 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000972 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000973 testOutsideTimeout = testInsideTimeout
974
975 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000976 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000978 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979
980 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000981 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
983
984
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000985class TCPTimeoutTest(SocketTCPTest):
986
987 def testTCPTimeout(self):
988 def raise_timeout(*args, **kwargs):
989 self.serv.settimeout(1.0)
990 self.serv.accept()
991 self.failUnlessRaises(socket.timeout, raise_timeout,
992 "Error generating a timeout exception (TCP)")
993
994 def testTimeoutZero(self):
995 ok = False
996 try:
997 self.serv.settimeout(0.0)
998 foo = self.serv.accept()
999 except socket.timeout:
1000 self.fail("caught timeout instead of error (TCP)")
1001 except socket.error:
1002 ok = True
1003 except:
1004 self.fail("caught unexpected exception (TCP)")
1005 if not ok:
1006 self.fail("accept() returned success when we did not expect it")
1007
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008 def testInterruptedTimeout(self):
1009 # XXX I don't know how to do this test on MSWindows or any other
1010 # plaform that doesn't support signal.alarm() or os.kill(), though
1011 # the bug should have existed on all platforms.
1012 if not hasattr(signal, "alarm"):
1013 return # can only test on *nix
1014 self.serv.settimeout(5.0) # must be longer than alarm
1015 class Alarm(Exception):
1016 pass
1017 def alarm_handler(signal, frame):
1018 raise Alarm
1019 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1020 try:
1021 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1022 try:
1023 foo = self.serv.accept()
1024 except socket.timeout:
1025 self.fail("caught timeout instead of Alarm")
1026 except Alarm:
1027 pass
1028 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001029 self.fail("caught other exception instead of Alarm:"
1030 " %s(%s):\n%s" %
1031 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001032 else:
1033 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001034 finally:
1035 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001036 except Alarm:
1037 self.fail("got Alarm in wrong place")
1038 finally:
1039 # no alarm can be pending. Safe to restore old handler.
1040 signal.signal(signal.SIGALRM, old_alarm)
1041
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001042class UDPTimeoutTest(SocketTCPTest):
1043
1044 def testUDPTimeout(self):
1045 def raise_timeout(*args, **kwargs):
1046 self.serv.settimeout(1.0)
1047 self.serv.recv(1024)
1048 self.failUnlessRaises(socket.timeout, raise_timeout,
1049 "Error generating a timeout exception (UDP)")
1050
1051 def testTimeoutZero(self):
1052 ok = False
1053 try:
1054 self.serv.settimeout(0.0)
1055 foo = self.serv.recv(1024)
1056 except socket.timeout:
1057 self.fail("caught timeout instead of error (UDP)")
1058 except socket.error:
1059 ok = True
1060 except:
1061 self.fail("caught unexpected exception (UDP)")
1062 if not ok:
1063 self.fail("recv() returned success when we did not expect it")
1064
1065class TestExceptions(unittest.TestCase):
1066
1067 def testExceptionTree(self):
1068 self.assert_(issubclass(socket.error, Exception))
1069 self.assert_(issubclass(socket.herror, socket.error))
1070 self.assert_(issubclass(socket.gaierror, socket.error))
1071 self.assert_(issubclass(socket.timeout, socket.error))
1072
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001073class TestLinuxAbstractNamespace(unittest.TestCase):
1074
1075 UNIX_PATH_MAX = 108
1076
1077 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001078 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1080 s1.bind(address)
1081 s1.listen(1)
1082 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1083 s2.connect(s1.getsockname())
1084 s1.accept()
1085 self.assertEqual(s1.getsockname(), address)
1086 self.assertEqual(s2.getpeername(), address)
1087
1088 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001089 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001090 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1091 s.bind(address)
1092 self.assertEqual(s.getsockname(), address)
1093
1094 def testNameOverflow(self):
1095 address = "\x00" + "h" * self.UNIX_PATH_MAX
1096 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1097 self.assertRaises(socket.error, s.bind, address)
1098
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001099
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100class BufferIOTest(SocketConnectedTest):
1101 """
1102 Test the buffer versions of socket.recv() and socket.send().
1103 """
1104 def __init__(self, methodName='runTest'):
1105 SocketConnectedTest.__init__(self, methodName=methodName)
1106
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001107 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001108 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001109 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001111 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 self.assertEqual(msg, MSG)
1113
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001114 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001115 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001116 self.serv_conn.send(buf)
1117
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001118 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001119 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001120 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001122 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 self.assertEqual(msg, MSG)
1124
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001125 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001126 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 self.serv_conn.send(buf)
1128
Christian Heimes043d6f62008-01-07 17:19:16 +00001129
1130TIPC_STYPE = 2000
1131TIPC_LOWER = 200
1132TIPC_UPPER = 210
1133
1134def isTipcAvailable():
1135 """Check if the TIPC module is loaded
1136
1137 The TIPC module is not loaded automatically on Ubuntu and probably
1138 other Linux distros.
1139 """
1140 if not hasattr(socket, "AF_TIPC"):
1141 return False
1142 if not os.path.isfile("/proc/modules"):
1143 return False
1144 with open("/proc/modules") as f:
1145 for line in f:
1146 if line.startswith("tipc "):
1147 return True
Christian Heimes2380ac72008-01-09 00:17:24 +00001148 if test_support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001149 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1150 return False
1151
1152class TIPCTest (unittest.TestCase):
1153 def testRDM(self):
1154 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1155 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1156
1157 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1158 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1159 TIPC_LOWER, TIPC_UPPER)
1160 srv.bind(srvaddr)
1161
1162 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1163 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1164 cli.sendto(MSG, sendaddr)
1165
1166 msg, recvaddr = srv.recvfrom(1024)
1167
1168 self.assertEqual(cli.getsockname(), recvaddr)
1169 self.assertEqual(msg, MSG)
1170
1171
1172class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1173 def __init__(self, methodName = 'runTest'):
1174 unittest.TestCase.__init__(self, methodName = methodName)
1175 ThreadableTest.__init__(self)
1176
1177 def setUp(self):
1178 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1179 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1180 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1181 TIPC_LOWER, TIPC_UPPER)
1182 self.srv.bind(srvaddr)
1183 self.srv.listen(5)
1184 self.serverExplicitReady()
1185 self.conn, self.connaddr = self.srv.accept()
1186
1187 def clientSetUp(self):
1188 # The is a hittable race between serverExplicitReady() and the
1189 # accept() call; sleep a little while to avoid it, otherwise
1190 # we could get an exception
1191 time.sleep(0.1)
1192 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1193 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1194 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1195 self.cli.connect(addr)
1196 self.cliaddr = self.cli.getsockname()
1197
1198 def testStream(self):
1199 msg = self.conn.recv(1024)
1200 self.assertEqual(msg, MSG)
1201 self.assertEqual(self.cliaddr, self.connaddr)
1202
1203 def _testStream(self):
1204 self.cli.send(MSG)
1205 self.cli.close()
1206
1207
Guido van Rossumb995eb72002-07-31 16:08:40 +00001208def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001209 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001210 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001211 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001212 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001213
1214 tests.extend([
1215 NonBlockingTCPTests,
1216 FileObjectClassTestCase,
1217 UnbufferedFileObjectClassTestCase,
1218 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001219 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220 NetworkConnectionNoServer,
1221 NetworkConnectionAttributesTest,
1222 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001223 ])
Dave Cole331708b2004-08-09 04:51:41 +00001224 if hasattr(socket, "socketpair"):
1225 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001226 if sys.platform == 'linux2':
1227 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001228 if isTipcAvailable():
1229 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001230 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001231
1232 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001233 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001234 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001235
1236if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001237 test_main()