blob: c01d998ae0b39d4991044f502be5c488b68e0b98 [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__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000128 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000129 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):
Collin Winter3add4d72007-08-29 23:37:32 +0000136 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000137
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',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000341 'freebsd7', 'freebsd8', '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
Guido van Rossum540d9872007-08-17 03:51:09 +0000427 self.assertEquals(b'\x00' * 16, f('::'))
428 self.assertEquals(b'\x00' * 16, f('0::0'))
429 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000430 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
Guido van Rossum540d9872007-08-17 03:51:09 +0000461 self.assertEquals('::', f(b'\x00' * 16))
462 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000463 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
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000578 def testDup(self):
579 # Testing dup()
580 sock = self.cli_conn.dup()
581 msg = sock.recv(1024)
582 self.assertEqual(msg, MSG)
583
584 def _testDup(self):
585 self.serv_conn.send(MSG)
586
Guido van Rossum24e4af82002-06-12 19:18:08 +0000587 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000588 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000589 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000590 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000591
592 def _testShutdown(self):
593 self.serv_conn.send(MSG)
594 self.serv_conn.shutdown(2)
595
596class BasicUDPTest(ThreadedUDPSocketTest):
597
598 def __init__(self, methodName='runTest'):
599 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
600
601 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000602 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000603 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000604 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000605
606 def _testSendtoAndRecv(self):
607 self.cli.sendto(MSG, 0, (HOST, PORT))
608
Guido van Rossum1c938012002-06-12 21:17:20 +0000609 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000610 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000611 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000612 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000613
Guido van Rossum1c938012002-06-12 21:17:20 +0000614 def _testRecvFrom(self):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000615 self.cli.sendto(MSG, 0, (HOST, PORT))
616
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 def testRecvFromNegative(self):
618 # Negative lengths passed to recvfrom should give ValueError.
619 self.assertRaises(ValueError, self.serv.recvfrom, -1)
620
621 def _testRecvFromNegative(self):
622 self.cli.sendto(MSG, 0, (HOST, PORT))
623
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624class TCPCloserTest(ThreadedTCPSocketTest):
625
626 def testClose(self):
627 conn, addr = self.serv.accept()
628 conn.close()
629
630 sd = self.cli
631 read, write, err = select.select([sd], [], [], 1.0)
632 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000633 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000635 # Calling close() many times should be safe.
636 conn.close()
637 conn.close()
638
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639 def _testClose(self):
640 self.cli.connect((HOST, PORT))
641 time.sleep(1.0)
642
Dave Cole331708b2004-08-09 04:51:41 +0000643class BasicSocketPairTest(SocketPairTest):
644
645 def __init__(self, methodName='runTest'):
646 SocketPairTest.__init__(self, methodName=methodName)
647
648 def testRecv(self):
649 msg = self.serv.recv(1024)
650 self.assertEqual(msg, MSG)
651
652 def _testRecv(self):
653 self.cli.send(MSG)
654
655 def testSend(self):
656 self.serv.send(MSG)
657
658 def _testSend(self):
659 msg = self.cli.recv(1024)
660 self.assertEqual(msg, MSG)
661
Guido van Rossum24e4af82002-06-12 19:18:08 +0000662class NonBlockingTCPTests(ThreadedTCPSocketTest):
663
664 def __init__(self, methodName='runTest'):
665 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
666
667 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000668 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000669 self.serv.setblocking(0)
670 start = time.time()
671 try:
672 self.serv.accept()
673 except socket.error:
674 pass
675 end = time.time()
676 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
677
678 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000679 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000680
Guido van Rossum24e4af82002-06-12 19:18:08 +0000681 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000682 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000683 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000684 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000685 conn, addr = self.serv.accept()
686 except socket.error:
687 pass
688 else:
689 self.fail("Error trying to do non-blocking accept.")
690 read, write, err = select.select([self.serv], [], [])
691 if self.serv in read:
692 conn, addr = self.serv.accept()
693 else:
694 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000695
Guido van Rossum24e4af82002-06-12 19:18:08 +0000696 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000697 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000698 self.cli.connect((HOST, PORT))
699
700 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000701 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000702 conn, addr = self.serv.accept()
703
704 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000705 self.cli.settimeout(10)
706 self.cli.connect((HOST, PORT))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707
708 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000709 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710 conn, addr = self.serv.accept()
711 conn.setblocking(0)
712 try:
713 msg = conn.recv(len(MSG))
714 except socket.error:
715 pass
716 else:
717 self.fail("Error trying to do non-blocking recv.")
718 read, write, err = select.select([conn], [], [])
719 if conn in read:
720 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000721 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000722 else:
723 self.fail("Error during select call to non-blocking socket.")
724
725 def _testRecv(self):
726 self.cli.connect((HOST, PORT))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000727 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000728 self.cli.send(MSG)
729
730class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000731 """Unit tests for the object returned by socket.makefile()
732
733 self.serv_file is the io object returned by makefile() on
734 the client connection. You can read from this file to
735 get output from the server.
736
737 self.cli_file is the io object returned by makefile() on the
738 server connection. You can write to this file to send output
739 to the client.
740 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000741
Guido van Rossume9f66142002-08-07 15:46:19 +0000742 bufsize = -1 # Use default buffer size
743
Guido van Rossum24e4af82002-06-12 19:18:08 +0000744 def __init__(self, methodName='runTest'):
745 SocketConnectedTest.__init__(self, methodName=methodName)
746
747 def setUp(self):
748 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000749 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000750
751 def tearDown(self):
752 self.serv_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000753 self.assert_(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000754 self.serv_file = None
755 SocketConnectedTest.tearDown(self)
756
757 def clientSetUp(self):
758 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000759 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000760
761 def clientTearDown(self):
762 self.cli_file.close()
Tim Peters116d83c2004-03-28 02:20:45 +0000763 self.assert_(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000764 self.cli_file = None
765 SocketConnectedTest.clientTearDown(self)
766
767 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000768 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000769 first_seg = self.serv_file.read(len(MSG)-3)
770 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000771 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000772 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000773
774 def _testSmallRead(self):
775 self.cli_file.write(MSG)
776 self.cli_file.flush()
777
Guido van Rossum8c943832002-08-08 01:00:28 +0000778 def testFullRead(self):
779 # read until EOF
780 msg = self.serv_file.read()
781 self.assertEqual(msg, MSG)
782
783 def _testFullRead(self):
784 self.cli_file.write(MSG)
785 self.cli_file.close()
786
Guido van Rossum24e4af82002-06-12 19:18:08 +0000787 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000788 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000789 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000790 while 1:
791 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000792 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000793 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000794 buf += char
795 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000796
797 def _testUnbufferedRead(self):
798 self.cli_file.write(MSG)
799 self.cli_file.flush()
800
801 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000802 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000803 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000804 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000805
806 def _testReadline(self):
807 self.cli_file.write(MSG)
808 self.cli_file.flush()
809
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000810 def testCloseAfterMakefile(self):
811 # The file returned by makefile should keep the socket open.
812 self.cli_conn.close()
813 # read until EOF
814 msg = self.serv_file.read()
815 self.assertEqual(msg, MSG)
816
817 def _testCloseAfterMakefile(self):
818 self.cli_file.write(MSG)
819 self.cli_file.flush()
820
821 def testMakefileAfterMakefileClose(self):
822 self.serv_file.close()
823 msg = self.cli_conn.recv(len(MSG))
824 self.assertEqual(msg, MSG)
825
826 def _testMakefileAfterMakefileClose(self):
827 self.cli_file.write(MSG)
828 self.cli_file.flush()
829
Tim Peters116d83c2004-03-28 02:20:45 +0000830 def testClosedAttr(self):
831 self.assert_(not self.serv_file.closed)
832
833 def _testClosedAttr(self):
834 self.assert_(not self.cli_file.closed)
835
Guido van Rossume9f66142002-08-07 15:46:19 +0000836class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
837
838 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000839
Guido van Rossume9f66142002-08-07 15:46:19 +0000840 In this case (and in this case only), it should be possible to
841 create a file object, read a line from it, create another file
842 object, read another line from it, without loss of data in the
843 first file object's buffer. Note that httplib relies on this
844 when reading multiple requests from the same socket."""
845
846 bufsize = 0 # Use unbuffered mode
847
848 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000849 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000850 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000851 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000852 self.serv_file = self.cli_conn.makefile('rb', 0)
853 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000854 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000855
856 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000857 self.cli_file.write(b"A. " + MSG)
858 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000859 self.cli_file.flush()
860
Guido van Rossum8c943832002-08-08 01:00:28 +0000861class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
862
863 bufsize = 1 # Default-buffered for reading; line-buffered for writing
864
865
866class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
867
868 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000869
Thomas Woutersb2137042007-02-01 18:02:27 +0000870
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871class NetworkConnectionTest(object):
872 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000873
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 def clientSetUp(self):
875 self.cli = socket.create_connection((HOST, PORT))
876 self.serv_conn = self.cli
877
878class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
879 """Tests that NetworkConnection does not break existing TCP functionality.
880 """
881
882class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000883
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 def testWithoutServer(self):
885 self.failUnlessRaises(socket.error, lambda: socket.create_connection((HOST, PORT)))
886
887class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
888
889 def __init__(self, methodName='runTest'):
890 SocketTCPTest.__init__(self, methodName=methodName)
891 ThreadableTest.__init__(self)
892
893 def clientSetUp(self):
894 pass
895
896 def clientTearDown(self):
897 self.cli.close()
898 self.cli = None
899 ThreadableTest.clientTearDown(self)
900
901 def _justAccept(self):
902 conn, addr = self.serv.accept()
903
904 testFamily = _justAccept
905 def _testFamily(self):
906 self.cli = socket.create_connection((HOST, PORT), timeout=30)
907 self.assertEqual(self.cli.family, 2)
908
909 testTimeoutDefault = _justAccept
910 def _testTimeoutDefault(self):
911 self.cli = socket.create_connection((HOST, PORT))
912 self.assertTrue(self.cli.gettimeout() is None)
913
914 testTimeoutValueNamed = _justAccept
915 def _testTimeoutValueNamed(self):
916 self.cli = socket.create_connection((HOST, PORT), timeout=30)
917 self.assertEqual(self.cli.gettimeout(), 30)
918
919 testTimeoutValueNonamed = _justAccept
920 def _testTimeoutValueNonamed(self):
921 self.cli = socket.create_connection((HOST, PORT), 30)
922 self.assertEqual(self.cli.gettimeout(), 30)
923
924 testTimeoutNone = _justAccept
925 def _testTimeoutNone(self):
926 previous = socket.getdefaulttimeout()
927 socket.setdefaulttimeout(30)
928 try:
929 self.cli = socket.create_connection((HOST, PORT), timeout=None)
930 finally:
931 socket.setdefaulttimeout(previous)
932 self.assertEqual(self.cli.gettimeout(), 30)
933
934
935class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
936
937 def __init__(self, methodName='runTest'):
938 SocketTCPTest.__init__(self, methodName=methodName)
939 ThreadableTest.__init__(self)
940
941 def clientSetUp(self):
942 pass
943
944 def clientTearDown(self):
945 self.cli.close()
946 self.cli = None
947 ThreadableTest.clientTearDown(self)
948
949 def testInsideTimeout(self):
950 conn, addr = self.serv.accept()
951 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000952 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953 testOutsideTimeout = testInsideTimeout
954
955 def _testInsideTimeout(self):
956 self.cli = sock = socket.create_connection((HOST, PORT))
957 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000958 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959
960 def _testOutsideTimeout(self):
961 self.cli = sock = socket.create_connection((HOST, PORT), timeout=1)
962 self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
963
964
Raymond Hettinger11a35f52003-06-29 04:40:22 +0000965class TCPTimeoutTest(SocketTCPTest):
966
967 def testTCPTimeout(self):
968 def raise_timeout(*args, **kwargs):
969 self.serv.settimeout(1.0)
970 self.serv.accept()
971 self.failUnlessRaises(socket.timeout, raise_timeout,
972 "Error generating a timeout exception (TCP)")
973
974 def testTimeoutZero(self):
975 ok = False
976 try:
977 self.serv.settimeout(0.0)
978 foo = self.serv.accept()
979 except socket.timeout:
980 self.fail("caught timeout instead of error (TCP)")
981 except socket.error:
982 ok = True
983 except:
984 self.fail("caught unexpected exception (TCP)")
985 if not ok:
986 self.fail("accept() returned success when we did not expect it")
987
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000988 def testInterruptedTimeout(self):
989 # XXX I don't know how to do this test on MSWindows or any other
990 # plaform that doesn't support signal.alarm() or os.kill(), though
991 # the bug should have existed on all platforms.
992 if not hasattr(signal, "alarm"):
993 return # can only test on *nix
994 self.serv.settimeout(5.0) # must be longer than alarm
995 class Alarm(Exception):
996 pass
997 def alarm_handler(signal, frame):
998 raise Alarm
999 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1000 try:
1001 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1002 try:
1003 foo = self.serv.accept()
1004 except socket.timeout:
1005 self.fail("caught timeout instead of Alarm")
1006 except Alarm:
1007 pass
1008 except:
1009 self.fail("caught other exception instead of Alarm")
1010 else:
1011 self.fail("nothing caught")
1012 signal.alarm(0) # shut off alarm
1013 except Alarm:
1014 self.fail("got Alarm in wrong place")
1015 finally:
1016 # no alarm can be pending. Safe to restore old handler.
1017 signal.signal(signal.SIGALRM, old_alarm)
1018
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001019class UDPTimeoutTest(SocketTCPTest):
1020
1021 def testUDPTimeout(self):
1022 def raise_timeout(*args, **kwargs):
1023 self.serv.settimeout(1.0)
1024 self.serv.recv(1024)
1025 self.failUnlessRaises(socket.timeout, raise_timeout,
1026 "Error generating a timeout exception (UDP)")
1027
1028 def testTimeoutZero(self):
1029 ok = False
1030 try:
1031 self.serv.settimeout(0.0)
1032 foo = self.serv.recv(1024)
1033 except socket.timeout:
1034 self.fail("caught timeout instead of error (UDP)")
1035 except socket.error:
1036 ok = True
1037 except:
1038 self.fail("caught unexpected exception (UDP)")
1039 if not ok:
1040 self.fail("recv() returned success when we did not expect it")
1041
1042class TestExceptions(unittest.TestCase):
1043
1044 def testExceptionTree(self):
1045 self.assert_(issubclass(socket.error, Exception))
1046 self.assert_(issubclass(socket.herror, socket.error))
1047 self.assert_(issubclass(socket.gaierror, socket.error))
1048 self.assert_(issubclass(socket.timeout, socket.error))
1049
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050class TestLinuxAbstractNamespace(unittest.TestCase):
1051
1052 UNIX_PATH_MAX = 108
1053
1054 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001055 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001056 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1057 s1.bind(address)
1058 s1.listen(1)
1059 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1060 s2.connect(s1.getsockname())
1061 s1.accept()
1062 self.assertEqual(s1.getsockname(), address)
1063 self.assertEqual(s2.getpeername(), address)
1064
1065 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001066 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1068 s.bind(address)
1069 self.assertEqual(s.getsockname(), address)
1070
1071 def testNameOverflow(self):
1072 address = "\x00" + "h" * self.UNIX_PATH_MAX
1073 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1074 self.assertRaises(socket.error, s.bind, address)
1075
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001076
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077class BufferIOTest(SocketConnectedTest):
1078 """
1079 Test the buffer versions of socket.recv() and socket.send().
1080 """
1081 def __init__(self, methodName='runTest'):
1082 SocketConnectedTest.__init__(self, methodName=methodName)
1083
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001084 def testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001085 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001086 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001088 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089 self.assertEqual(msg, MSG)
1090
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001091 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001092 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093 self.serv_conn.send(buf)
1094
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001095 def testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001096 buf = b" "*1024
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001097 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001098 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001099 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100 self.assertEqual(msg, MSG)
1101
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001102 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001103 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001104 self.serv_conn.send(buf)
1105
Guido van Rossumb995eb72002-07-31 16:08:40 +00001106def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001107 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001108 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001109 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001110 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001111
1112 tests.extend([
1113 NonBlockingTCPTests,
1114 FileObjectClassTestCase,
1115 UnbufferedFileObjectClassTestCase,
1116 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001117 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 NetworkConnectionNoServer,
1119 NetworkConnectionAttributesTest,
1120 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001121 ])
Dave Cole331708b2004-08-09 04:51:41 +00001122 if hasattr(socket, "socketpair"):
1123 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001124 if sys.platform == 'linux2':
1125 tests.append(TestLinuxAbstractNamespace)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001126
1127 thread_info = test_support.threading_setup()
Walter Dörwald21d3a322003-05-01 17:45:56 +00001128 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001129 test_support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001130
1131if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001132 test_main()