blob: a8b65c410e1e0a65a80d25c79069aaedbfaa6494 [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001#!/usr/bin/env python
Barry Warsawcf3d4b51997-01-03 20:03:32 +00002
Guido van Rossum24e4af82002-06-12 19:18:08 +00003import unittest
Barry Warsaw04f357c2002-07-23 19:04:11 +00004from test import test_support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Barry Warsawcf3d4b51997-01-03 20:03:32 +00006import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00007import select
Barry Warsawcf3d4b51997-01-03 20:03:32 +00008import time
Guido van Rossum24e4af82002-06-12 19:18:08 +00009import thread, threading
10import Queue
Jack Jansen522e7692002-09-06 21:57:50 +000011import sys
Raymond Hettinger027bb632004-05-31 03:09:25 +000012from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000014
Guido van Rossum24e4af82002-06-12 19:18:08 +000015PORT = 50007
16HOST = 'localhost'
Guido van Rossum7d0a8262007-05-21 23:13:11 +000017MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000018
Guido van Rossum24e4af82002-06-12 19:18:08 +000019class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000020
Guido van Rossum24e4af82002-06-12 19:18:08 +000021 def setUp(self):
22 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
23 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024 global PORT
25 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000026 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000027
Guido van Rossum24e4af82002-06-12 19:18:08 +000028 def tearDown(self):
29 self.serv.close()
30 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000031
Guido van Rossum24e4af82002-06-12 19:18:08 +000032class SocketUDPTest(unittest.TestCase):
33
34 def setUp(self):
35 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
36 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000037 global PORT
38 PORT = test_support.bind_port(self.serv, HOST, PORT)
Guido van Rossum24e4af82002-06-12 19:18:08 +000039
40 def tearDown(self):
41 self.serv.close()
42 self.serv = None
43
44class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000045 """Threadable Test class
46
47 The ThreadableTest class makes it easy to create a threaded
48 client/server pair from an existing unit test. To create a
49 new threaded class from an existing unit test, use multiple
50 inheritance:
51
52 class NewClass (OldClass, ThreadableTest):
53 pass
54
55 This class defines two new fixture functions with obvious
56 purposes for overriding:
57
58 clientSetUp ()
59 clientTearDown ()
60
61 Any new test functions within the class must then define
62 tests in pairs, where the test name is preceeded with a
63 '_' to indicate the client portion of the test. Ex:
64
65 def testFoo(self):
66 # Server portion
67
68 def _testFoo(self):
69 # Client portion
70
71 Any exceptions raised by the clients during their tests
72 are caught and transferred to the main thread to alert
73 the testing framework.
74
75 Note, the server setup function cannot call any blocking
76 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +000077 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000078 the blocking call (such as in setting up a client/server
79 connection and performing the accept() in setUp().
80 """
Guido van Rossum24e4af82002-06-12 19:18:08 +000081
82 def __init__(self):
83 # Swap the true setup function
84 self.__setUp = self.setUp
85 self.__tearDown = self.tearDown
86 self.setUp = self._setUp
87 self.tearDown = self._tearDown
88
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000089 def serverExplicitReady(self):
90 """This method allows the server to explicitly indicate that
91 it wants the client thread to proceed. This is useful if the
92 server is about to execute a blocking routine that is
93 dependent upon the client thread during its setup routine."""
94 self.server_ready.set()
95
Guido van Rossum24e4af82002-06-12 19:18:08 +000096 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +000097 self.server_ready = threading.Event()
98 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +000099 self.done = threading.Event()
100 self.queue = Queue.Queue(1)
101
102 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000103 methodname = self.id()
104 i = methodname.rfind('.')
105 methodname = methodname[i+1:]
106 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000107 self.client_thread = thread.start_new_thread(
108 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000109
110 self.__setUp()
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000111 if not self.server_ready.isSet():
112 self.server_ready.set()
113 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000114
115 def _tearDown(self):
116 self.__tearDown()
117 self.done.wait()
118
119 if not self.queue.empty():
120 msg = self.queue.get()
121 self.fail(msg)
122
123 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000124 self.server_ready.wait()
125 self.client_ready.set()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000126 self.clientSetUp()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000127 if not hasattr(test_func, '__call__'):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000128 raise TypeError, "test_func must be a callable function"
129 try:
130 test_func()
Guido van Rossumb940e112007-01-10 16:19:56 +0000131 except Exception as strerror:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000132 self.queue.put(strerror)
133 self.clientTearDown()
134
135 def clientSetUp(self):
136 raise NotImplementedError, "clientSetUp must be implemented."
137
138 def clientTearDown(self):
139 self.done.set()
140 thread.exit()
141
142class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
143
144 def __init__(self, methodName='runTest'):
145 SocketTCPTest.__init__(self, methodName=methodName)
146 ThreadableTest.__init__(self)
147
148 def clientSetUp(self):
149 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
150
151 def clientTearDown(self):
152 self.cli.close()
153 self.cli = None
154 ThreadableTest.clientTearDown(self)
155
156class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
157
158 def __init__(self, methodName='runTest'):
159 SocketUDPTest.__init__(self, methodName=methodName)
160 ThreadableTest.__init__(self)
161
162 def clientSetUp(self):
163 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
164
165class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000166 """Socket tests for client-server connection.
167
168 self.cli_conn is a client socket connected to the server. The
169 setUp() method guarantees that it is connected to the server.
170 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000171
172 def __init__(self, methodName='runTest'):
173 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
174
175 def setUp(self):
176 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000177 # Indicate explicitly we're ready for the client thread to
178 # proceed and then perform the blocking call to accept
179 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000180 conn, addr = self.serv.accept()
181 self.cli_conn = conn
182
183 def tearDown(self):
184 self.cli_conn.close()
185 self.cli_conn = None
186 ThreadedTCPSocketTest.tearDown(self)
187
188 def clientSetUp(self):
189 ThreadedTCPSocketTest.clientSetUp(self)
190 self.cli.connect((HOST, PORT))
191 self.serv_conn = self.cli
192
193 def clientTearDown(self):
194 self.serv_conn.close()
195 self.serv_conn = None
196 ThreadedTCPSocketTest.clientTearDown(self)
197
Dave Cole331708b2004-08-09 04:51:41 +0000198class SocketPairTest(unittest.TestCase, ThreadableTest):
199
200 def __init__(self, methodName='runTest'):
201 unittest.TestCase.__init__(self, methodName=methodName)
202 ThreadableTest.__init__(self)
203
204 def setUp(self):
205 self.serv, self.cli = socket.socketpair()
206
207 def tearDown(self):
208 self.serv.close()
209 self.serv = None
210
211 def clientSetUp(self):
212 pass
213
214 def clientTearDown(self):
215 self.cli.close()
216 self.cli = None
217 ThreadableTest.clientTearDown(self)
218
Tim Peters494aaee2004-08-09 18:54:11 +0000219
Guido van Rossum24e4af82002-06-12 19:18:08 +0000220#######################################################################
221## Begin Tests
222
223class GeneralModuleTests(unittest.TestCase):
224
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000225 def test_repr(self):
226 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
227 self.assert_(repr(s).startswith("<socket.socket object"))
228
Raymond Hettinger027bb632004-05-31 03:09:25 +0000229 def test_weakref(self):
230 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
231 p = proxy(s)
232 self.assertEqual(p.fileno(), s.fileno())
233 s.close()
234 s = None
235 try:
236 p.fileno()
237 except ReferenceError:
238 pass
239 else:
240 self.fail('Socket proxy still exists')
241
Guido van Rossum24e4af82002-06-12 19:18:08 +0000242 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000243 # Testing socket module exceptions
Guido van Rossum24e4af82002-06-12 19:18:08 +0000244 def raise_error(*args, **kwargs):
245 raise socket.error
246 def raise_herror(*args, **kwargs):
247 raise socket.herror
248 def raise_gaierror(*args, **kwargs):
249 raise socket.gaierror
250 self.failUnlessRaises(socket.error, raise_error,
251 "Error raising socket exception.")
252 self.failUnlessRaises(socket.error, raise_herror,
253 "Error raising socket exception.")
254 self.failUnlessRaises(socket.error, raise_gaierror,
255 "Error raising socket exception.")
256
257 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000258 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259 socket.AF_INET
260 socket.SOCK_STREAM
261 socket.SOCK_DGRAM
262 socket.SOCK_RAW
263 socket.SOCK_RDM
264 socket.SOCK_SEQPACKET
265 socket.SOL_SOCKET
266 socket.SO_REUSEADDR
267
Guido van Rossum654c11e2002-06-13 20:24:17 +0000268 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000269 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000270 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000271 try:
272 ip = socket.gethostbyname(hostname)
273 except socket.error:
274 # Probably name lookup wasn't set up right; skip this test
275 return
Guido van Rossum654c11e2002-06-13 20:24:17 +0000276 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000277 try:
278 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
279 except socket.error:
280 # Probably a similar problem as above; skip this test
281 return
Brett Cannon01668a12005-03-11 00:04:17 +0000282 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000284 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000285 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000286
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000287 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000288 # Testing reference count for getnameinfo
Guido van Rossum24e4af82002-06-12 19:18:08 +0000289 import sys
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000290 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000291 try:
292 # On some versions, this loses a reference
293 orig = sys.getrefcount(__name__)
294 socket.getnameinfo(__name__,0)
295 except SystemError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000296 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000297 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000298
Guido van Rossum24e4af82002-06-12 19:18:08 +0000299 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000300 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000301 try:
302 # On some versions, this crashes the interpreter.
303 socket.getnameinfo(('x', 0, 0, 0), 0)
304 except socket.error:
305 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000306
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000307 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000308 # This just checks that htons etc. are their own inverse,
309 # when looking at the lower 16 or 32 bits.
310 sizes = {socket.htonl: 32, socket.ntohl: 32,
311 socket.htons: 16, socket.ntohs: 16}
312 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000313 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000314 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
315 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000316
Guido van Rossuma2627af2002-09-14 00:58:46 +0000317 swapped = func(mask)
318 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000319 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000320
Guido van Rossum018919a2007-01-15 00:07:32 +0000321 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000322 good_values = [ 1, 2, 3, 1, 2, 3 ]
323 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000324 for k in good_values:
325 socket.ntohl(k)
326 socket.ntohs(k)
327 socket.htonl(k)
328 socket.htons(k)
329 for k in bad_values:
330 self.assertRaises(OverflowError, socket.ntohl, k)
331 self.assertRaises(OverflowError, socket.ntohs, k)
332 self.assertRaises(OverflowError, socket.htonl, k)
333 self.assertRaises(OverflowError, socket.htons, k)
334
Barry Warsaw11b91a02004-06-28 00:50:43 +0000335 def testGetServBy(self):
336 eq = self.assertEqual
337 # Find one service that exists, then check all the related interfaces.
338 # I've ordered this by protocols that have both a tcp and udp
339 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000340 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Hye-Shik Chang4e422812005-07-17 02:36:59 +0000341 'freebsd7', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000342 # avoid the 'echo' service on this platform, as there is an
343 # assumption breaking non-standard port/protocol entry
344 services = ('daytime', 'qotd', 'domain')
345 else:
346 services = ('echo', 'daytime', 'domain')
347 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000348 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000349 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000350 break
351 except socket.error:
352 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000353 else:
354 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000355 # Try same call with optional protocol omitted
356 port2 = socket.getservbyname(service)
357 eq(port, port2)
358 # Try udp, but don't barf it it doesn't exist
359 try:
360 udpport = socket.getservbyname(service, 'udp')
361 except socket.error:
362 udpport = None
363 else:
364 eq(udpport, port)
365 # Now make sure the lookup by port returns the same service name
366 eq(socket.getservbyport(port2), service)
367 eq(socket.getservbyport(port, 'tcp'), service)
368 if udpport is not None:
369 eq(socket.getservbyport(udpport, 'udp'), service)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000370
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000371 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000372 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000373 # The default timeout should initially be None
374 self.assertEqual(socket.getdefaulttimeout(), None)
375 s = socket.socket()
376 self.assertEqual(s.gettimeout(), None)
377 s.close()
378
379 # Set the default timeout to 10, and see if it propagates
380 socket.setdefaulttimeout(10)
381 self.assertEqual(socket.getdefaulttimeout(), 10)
382 s = socket.socket()
383 self.assertEqual(s.gettimeout(), 10)
384 s.close()
385
386 # Reset the default timeout to None, and see if it propagates
387 socket.setdefaulttimeout(None)
388 self.assertEqual(socket.getdefaulttimeout(), None)
389 s = socket.socket()
390 self.assertEqual(s.gettimeout(), None)
391 s.close()
392
393 # Check that setting it to an invalid value raises ValueError
394 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
395
396 # Check that setting it to an invalid type raises TypeError
397 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
398
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000399 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000400 if not hasattr(socket, 'inet_pton'):
401 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000402 from socket import inet_aton as f, inet_pton, AF_INET
403 g = lambda a: inet_pton(AF_INET, a)
404
Guido van Rossumb5b22702007-05-18 18:55:53 +0000405 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
406 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
407 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
408 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
409 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000410
Guido van Rossumb5b22702007-05-18 18:55:53 +0000411 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
412 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
413 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
414 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000415
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000416 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000417 if not hasattr(socket, 'inet_pton'):
418 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000419 try:
420 from socket import inet_pton, AF_INET6, has_ipv6
421 if not has_ipv6:
422 return
423 except ImportError:
424 return
425 f = lambda a: inet_pton(AF_INET6, a)
426
427 self.assertEquals('\x00' * 16, f('::'))
428 self.assertEquals('\x00' * 16, f('0::0'))
429 self.assertEquals('\x00\x01' + '\x00' * 14, f('1::'))
430 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000431 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 +0000432 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
433 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000434
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000435 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000436 if not hasattr(socket, 'inet_ntop'):
437 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000438 from socket import inet_ntoa as f, inet_ntop, AF_INET
439 g = lambda a: inet_ntop(AF_INET, a)
440
Guido van Rossumb5b22702007-05-18 18:55:53 +0000441 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
442 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
443 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
444 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000445
Guido van Rossumb5b22702007-05-18 18:55:53 +0000446 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
447 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
448 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000449
450 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000451 if not hasattr(socket, 'inet_ntop'):
452 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000453 try:
454 from socket import inet_ntop, AF_INET6, has_ipv6
455 if not has_ipv6:
456 return
457 except ImportError:
458 return
459 f = lambda a: inet_ntop(AF_INET6, a)
460
461 self.assertEquals('::', f('\x00' * 16))
462 self.assertEquals('::1', f('\x00' * 15 + '\x01'))
463 self.assertEquals(
464 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000465 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 +0000466 )
467
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000468 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000469
Guido van Rossum24e4af82002-06-12 19:18:08 +0000470 def testSockName(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000471 # Testing getsockname()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000472 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Guido van Rossum1c938012002-06-12 21:17:20 +0000473 sock.bind(("0.0.0.0", PORT+1))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000474 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000475 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
476 # it reasonable to get the host's addr in addition to 0.0.0.0.
477 # At least for eCos. This is required for the S/390 to pass.
478 my_ip_addr = socket.gethostbyname(socket.gethostname())
479 self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
480 self.assertEqual(name[1], PORT+1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000481
482 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000483 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000484 # We know a socket should start without reuse==0
485 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
486 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000487 self.failIf(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000488
489 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000490 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000491 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
492 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
493 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Guido van Rossum733632a2002-06-12 20:46:49 +0000494 self.failIf(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000495
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000496 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000497 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000498 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
499 sock.settimeout(1)
500 sock.close()
501 self.assertRaises(socket.error, sock.send, "spam")
502
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000503 def testNewAttributes(self):
504 # testing .family, .type and .protocol
505 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
506 self.assertEqual(sock.family, socket.AF_INET)
507 self.assertEqual(sock.type, socket.SOCK_STREAM)
508 self.assertEqual(sock.proto, 0)
509 sock.close()
510
Guido van Rossum24e4af82002-06-12 19:18:08 +0000511class BasicTCPTest(SocketConnectedTest):
512
513 def __init__(self, methodName='runTest'):
514 SocketConnectedTest.__init__(self, methodName=methodName)
515
516 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000517 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000518 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000519 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000520
521 def _testRecv(self):
522 self.serv_conn.send(MSG)
523
524 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000525 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000526 seg1 = self.cli_conn.recv(len(MSG) - 3)
527 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000528 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000529 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000530
531 def _testOverFlowRecv(self):
532 self.serv_conn.send(MSG)
533
534 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000535 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000536 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000537 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000538
539 def _testRecvFrom(self):
540 self.serv_conn.send(MSG)
541
542 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000543 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000544 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
545 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000546 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000547 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000548
549 def _testOverFlowRecvFrom(self):
550 self.serv_conn.send(MSG)
551
552 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000553 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000554 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000555 while 1:
556 read = self.cli_conn.recv(1024)
557 if not read:
558 break
Guido van Rossume531e292002-08-08 20:28:34 +0000559 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000560 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000561
562 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000563 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000564 self.serv_conn.sendall(big_chunk)
565
566 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000567 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000568 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000569 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000570 fd = self.cli_conn.fileno()
571 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
572 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000573 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000574
575 def _testFromFd(self):
576 self.serv_conn.send(MSG)
577
578 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000579 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000580 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000581 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000582
583 def _testShutdown(self):
584 self.serv_conn.send(MSG)
585 self.serv_conn.shutdown(2)
586
587class BasicUDPTest(ThreadedUDPSocketTest):
588
589 def __init__(self, methodName='runTest'):
590 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
591
592 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000593 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000594 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000595 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000596
597 def _testSendtoAndRecv(self):
598 self.cli.sendto(MSG, 0, (HOST, PORT))
599
Guido van Rossum1c938012002-06-12 21:17:20 +0000600 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000601 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000602 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000603 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000604
Guido van Rossum1c938012002-06-12 21:17:20 +0000605 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000606 self.cli.sendto(MSG, 0, (HOST, PORT))
607
Guido van Rossumd8faa362007-04-27 19:54:29 +0000608 def testRecvFromNegative(self):
609 # Negative lengths passed to recvfrom should give ValueError.
610 self.assertRaises(ValueError, self.serv.recvfrom, -1)
611
612 def _testRecvFromNegative(self):
613 self.cli.sendto(MSG, 0, (HOST, PORT))
614
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000615class TCPCloserTest(ThreadedTCPSocketTest):
616
617 def testClose(self):
618 conn, addr = self.serv.accept()
619 conn.close()
620
621 sd = self.cli
622 read, write, err = select.select([sd], [], [], 1.0)
623 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000624 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000626 # Calling close() many times should be safe.
627 conn.close()
628 conn.close()
629
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630 def _testClose(self):
631 self.cli.connect((HOST, PORT))
632 time.sleep(1.0)
633
Dave Cole331708b2004-08-09 04:51:41 +0000634class BasicSocketPairTest(SocketPairTest):
635
636 def __init__(self, methodName='runTest'):
637 SocketPairTest.__init__(self, methodName=methodName)
638
639 def testRecv(self):
640 msg = self.serv.recv(1024)
641 self.assertEqual(msg, MSG)
642
643 def _testRecv(self):
644 self.cli.send(MSG)
645
646 def testSend(self):
647 self.serv.send(MSG)
648
649 def _testSend(self):
650 msg = self.cli.recv(1024)
651 self.assertEqual(msg, MSG)
652
Guido van Rossum24e4af82002-06-12 19:18:08 +0000653class NonBlockingTCPTests(ThreadedTCPSocketTest):
654
655 def __init__(self, methodName='runTest'):
656 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
657
658 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000659 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000660 self.serv.setblocking(0)
661 start = time.time()
662 try:
663 self.serv.accept()
664 except socket.error:
665 pass
666 end = time.time()
667 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
668
669 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000670 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000671
Guido van Rossum24e4af82002-06-12 19:18:08 +0000672 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000673 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000674 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000675 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000676 conn, addr = self.serv.accept()
677 except socket.error:
678 pass
679 else:
680 self.fail("Error trying to do non-blocking accept.")
681 read, write, err = select.select([self.serv], [], [])
682 if self.serv in read:
683 conn, addr = self.serv.accept()
684 else:
685 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000686
Guido van Rossum24e4af82002-06-12 19:18:08 +0000687 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000688 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000689 self.cli.connect((HOST, PORT))
690
691 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000692 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000693 conn, addr = self.serv.accept()
694
695 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000696 self.cli.settimeout(10)
697 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000698
699 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000700 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000701 conn, addr = self.serv.accept()
702 conn.setblocking(0)
703 try:
704 msg = conn.recv(len(MSG))
705 except socket.error:
706 pass
707 else:
708 self.fail("Error trying to do non-blocking recv.")
709 read, write, err = select.select([conn], [], [])
710 if conn in read:
711 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000712 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713 else:
714 self.fail("Error during select call to non-blocking socket.")
715
716 def _testRecv(self):
717 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000718 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000719 self.cli.send(MSG)
720
721class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000722 """Unit tests for the object returned by socket.makefile()
723
724 self.serv_file is the io object returned by makefile() on
725 the client connection. You can read from this file to
726 get output from the server.
727
728 self.cli_file is the io object returned by makefile() on the
729 server connection. You can write to this file to send output
730 to the client.
731 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732
Guido van Rossume9f66142002-08-07 15:46:19 +0000733 bufsize = -1 # Use default buffer size
734
Guido van Rossum24e4af82002-06-12 19:18:08 +0000735 def __init__(self, methodName='runTest'):
736 SocketConnectedTest.__init__(self, methodName=methodName)
737
738 def setUp(self):
739 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000740 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000741
742 def tearDown(self):
743 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000744 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000745 self.serv_file = None
746 SocketConnectedTest.tearDown(self)
747
748 def clientSetUp(self):
749 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000750 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000751
752 def clientTearDown(self):
753 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000754 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755 self.cli_file = None
756 SocketConnectedTest.clientTearDown(self)
757
758 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000759 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000760 first_seg = self.serv_file.read(len(MSG)-3)
761 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000762 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000763 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764
765 def _testSmallRead(self):
766 self.cli_file.write(MSG)
767 self.cli_file.flush()
768
Guido van Rossum8c943832002-08-08 01:00:28 +0000769 def testFullRead(self):
770 # read until EOF
771 msg = self.serv_file.read()
772 self.assertEqual(msg, MSG)
773
774 def _testFullRead(self):
775 self.cli_file.write(MSG)
776 self.cli_file.close()
777
Guido van Rossum24e4af82002-06-12 19:18:08 +0000778 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000779 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000780 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000781 while 1:
782 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000783 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000784 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000785 buf += char
786 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000787
788 def _testUnbufferedRead(self):
789 self.cli_file.write(MSG)
790 self.cli_file.flush()
791
792 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000793 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000794 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000795 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000796
797 def _testReadline(self):
798 self.cli_file.write(MSG)
799 self.cli_file.flush()
800
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000801 def testCloseAfterMakefile(self):
802 # The file returned by makefile should keep the socket open.
803 self.cli_conn.close()
804 # read until EOF
805 msg = self.serv_file.read()
806 self.assertEqual(msg, MSG)
807
808 def _testCloseAfterMakefile(self):
809 self.cli_file.write(MSG)
810 self.cli_file.flush()
811
812 def testMakefileAfterMakefileClose(self):
813 self.serv_file.close()
814 msg = self.cli_conn.recv(len(MSG))
815 self.assertEqual(msg, MSG)
816
817 def _testMakefileAfterMakefileClose(self):
818 self.cli_file.write(MSG)
819 self.cli_file.flush()
820
Tim Peters116d83c2004-03-28 02:20:45 +0000821 def testClosedAttr(self):
822 self.assert_(not self.serv_file.closed)
823
824 def _testClosedAttr(self):
825 self.assert_(not self.cli_file.closed)
826
Guido van Rossume9f66142002-08-07 15:46:19 +0000827class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
828
829 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000830
Guido van Rossume9f66142002-08-07 15:46:19 +0000831 In this case (and in this case only), it should be possible to
832 create a file object, read a line from it, create another file
833 object, read another line from it, without loss of data in the
834 first file object's buffer. Note that httplib relies on this
835 when reading multiple requests from the same socket."""
836
837 bufsize = 0 # Use unbuffered mode
838
839 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000840 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000841 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000842 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000843 self.serv_file = self.cli_conn.makefile('rb', 0)
844 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000845 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000846
847 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000848 self.cli_file.write(b"A. " + MSG)
849 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000850 self.cli_file.flush()
851
Guido van Rossum8c943832002-08-08 01:00:28 +0000852class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
853
854 bufsize = 1 # Default-buffered for reading; line-buffered for writing
855
856
857class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
858
859 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000860
Thomas Woutersb2137042007-02-01 18:02:27 +0000861
Guido van Rossumd8faa362007-04-27 19:54:29 +0000862class NetworkConnectionTest(object):
863 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000864
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865 def clientSetUp(self):
866 self.cli = socket.create_connection((HOST, PORT))
867 self.serv_conn = self.cli
868
869class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
870 """Tests that NetworkConnection does not break existing TCP functionality.
871 """
872
873class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000874
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 def testWithoutServer(self):
876 self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
877
878class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
879
880 def __init__(self, methodName='runTest'):
881 SocketTCPTest.__init__(self, methodName=methodName)
882 ThreadableTest.__init__(self)
883
884 def clientSetUp(self):
885 pass
886
887 def clientTearDown(self):
888 self.cli.close()
889 self.cli = None
890 ThreadableTest.clientTearDown(self)
891
892 def _justAccept(self):
893 conn, addr = self.serv.accept()
894
895 testFamily = _justAccept
896 def _testFamily(self):
897 self.cli = socket.create_connection((HOST, PORT), timeout=30)
898 self.assertEqual(self.cli.family, 2)
899
900 testTimeoutDefault = _justAccept
901 def _testTimeoutDefault(self):
902 self.cli = socket.create_connection((HOST, PORT))
903 self.assertTrue(self.cli.gettimeout() is None)
904
905 testTimeoutValueNamed = _justAccept
906 def _testTimeoutValueNamed(self):
907 self.cli = socket.create_connection((HOST, PORT), timeout=30)
908 self.assertEqual(self.cli.gettimeout(), 30)
909
910 testTimeoutValueNonamed = _justAccept
911 def _testTimeoutValueNonamed(self):
912 self.cli = socket.create_connection((HOST, PORT), 30)
913 self.assertEqual(self.cli.gettimeout(), 30)
914
915 testTimeoutNone = _justAccept
916 def _testTimeoutNone(self):
917 previous = socket.getdefaulttimeout()
918 socket.setdefaulttimeout(30)
919 try:
920 self.cli = socket.create_connection((HOST, PORT), timeout=None)
921 finally:
922 socket.setdefaulttimeout(previous)
923 self.assertEqual(self.cli.gettimeout(), 30)
924
925
926class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
927
928 def __init__(self, methodName='runTest'):
929 SocketTCPTest.__init__(self, methodName=methodName)
930 ThreadableTest.__init__(self)
931
932 def clientSetUp(self):
933 pass
934
935 def clientTearDown(self):
936 self.cli.close()
937 self.cli = None
938 ThreadableTest.clientTearDown(self)
939
940 def testInsideTimeout(self):
941 conn, addr = self.serv.accept()
942 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000943 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944 testOutsideTimeout = testInsideTimeout
945
946 def _testInsideTimeout(self):
947 self.cli = sock = socket.create_connection((HOST, PORT))
948 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000949 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950
951 def _testOutsideTimeout(self):
952 self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
953 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
954
955
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000956class TCPTimeoutTest(SocketTCPTest):
957
958 def testTCPTimeout(self):
959 def raise_timeout(*args, **kwargs):
960 self.serv.settimeout(1.0)
961 self.serv.accept()
962 self.failUnlessRaises(socket.timeout, raise_timeout,
963 "Error generating a timeout exception (TCP)")
964
965 def testTimeoutZero(self):
966 ok = False
967 try:
968 self.serv.settimeout(0.0)
969 foo = self.serv.accept()
970 except socket.timeout:
971 self.fail("caught timeout instead of error (TCP)")
972 except socket.error:
973 ok = True
974 except:
975 self.fail("caught unexpected exception (TCP)")
976 if not ok:
977 self.fail("accept() returned success when we did not expect it")
978
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979 def testInterruptedTimeout(self):
980 # XXX I don't know how to do this test on MSWindows or any other
981 # plaform that doesn't support signal.alarm() or os.kill(), though
982 # the bug should have existed on all platforms.
983 if not hasattr(signal, "alarm"):
984 return # can only test on *nix
985 self.serv.settimeout(5.0) # must be longer than alarm
986 class Alarm(Exception):
987 pass
988 def alarm_handler(signal, frame):
989 raise Alarm
990 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
991 try:
992 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
993 try:
994 foo = self.serv.accept()
995 except socket.timeout:
996 self.fail("caught timeout instead of Alarm")
997 except Alarm:
998 pass
999 except:
1000 self.fail("caught other exception instead of Alarm")
1001 else:
1002 self.fail("nothing caught")
1003 signal.alarm(0) # shut off alarm
1004 except Alarm:
1005 self.fail("got Alarm in wrong place")
1006 finally:
1007 # no alarm can be pending. Safe to restore old handler.
1008 signal.signal(signal.SIGALRM, old_alarm)
1009
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001010class UDPTimeoutTest(SocketTCPTest):
1011
1012 def testUDPTimeout(self):
1013 def raise_timeout(*args, **kwargs):
1014 self.serv.settimeout(1.0)
1015 self.serv.recv(1024)
1016 self.failUnlessRaises(socket.timeout, raise_timeout,
1017 "Error generating a timeout exception (UDP)")
1018
1019 def testTimeoutZero(self):
1020 ok = False
1021 try:
1022 self.serv.settimeout(0.0)
1023 foo = self.serv.recv(1024)
1024 except socket.timeout:
1025 self.fail("caught timeout instead of error (UDP)")
1026 except socket.error:
1027 ok = True
1028 except:
1029 self.fail("caught unexpected exception (UDP)")
1030 if not ok:
1031 self.fail("recv() returned success when we did not expect it")
1032
1033class TestExceptions(unittest.TestCase):
1034
1035 def testExceptionTree(self):
1036 self.assert_(issubclass(socket.error, Exception))
1037 self.assert_(issubclass(socket.herror, socket.error))
1038 self.assert_(issubclass(socket.gaierror, socket.error))
1039 self.assert_(issubclass(socket.timeout, socket.error))
1040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001041class TestLinuxAbstractNamespace(unittest.TestCase):
1042
1043 UNIX_PATH_MAX = 108
1044
1045 def testLinuxAbstractNamespace(self):
1046 address = "\x00python-test-hello\x00\xff"
1047 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1048 s1.bind(address)
1049 s1.listen(1)
1050 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1051 s2.connect(s1.getsockname())
1052 s1.accept()
1053 self.assertEqual(s1.getsockname(), address)
1054 self.assertEqual(s2.getpeername(), address)
1055
1056 def testMaxName(self):
1057 address = "\x00" + "h" * (self.UNIX_PATH_MAX - 1)
1058 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1059 s.bind(address)
1060 self.assertEqual(s.getsockname(), address)
1061
1062 def testNameOverflow(self):
1063 address = "\x00" + "h" * self.UNIX_PATH_MAX
1064 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1065 self.assertRaises(socket.error, s.bind, address)
1066
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001067
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068class BufferIOTest(SocketConnectedTest):
1069 """
1070 Test the buffer versions of socket.recv() and socket.send().
1071 """
1072 def __init__(self, methodName='runTest'):
1073 SocketConnectedTest.__init__(self, methodName=methodName)
1074
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001075 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001076 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001077 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001079 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080 self.assertEqual(msg, MSG)
1081
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001082 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001083 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 self.serv_conn.send(buf)
1085
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001086 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001087 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001088 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001090 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 self.assertEqual(msg, MSG)
1092
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001093 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001094 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001095 self.serv_conn.send(buf)
1096
Guido van Rossumb995eb72002-07-31 16:08:40 +00001097def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001098 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001100 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001101 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001102
1103 tests.extend([
1104 NonBlockingTCPTests,
1105 FileObjectClassTestCase,
1106 UnbufferedFileObjectClassTestCase,
1107 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001108 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109 NetworkConnectionNoServer,
1110 NetworkConnectionAttributesTest,
1111 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001112 ])
Dave Cole331708b2004-08-09 04:51:41 +00001113 if hasattr(socket, "socketpair"):
1114 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001115 if sys.platform == 'linux2':
1116 tests.append(TestLinuxAbstractNamespace)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001117
1118 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001119 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001121
1122if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001123 test_main()