blob: 0f0cb80c1635d3309c79297b25a697a3d2ec6aa0 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00005
Christian Heimes5e696852008-04-09 08:37:03 +00006import errno
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Georg Brandl2067bfd2008-05-25 13:05:15 +00009import _thread as thread
10import threading
Christian Heimesbbe741d2008-03-28 10:53:29 +000011import time
12import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000013import queue
Jack Jansen522e7692002-09-06 21:57:50 +000014import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000015import os
16import array
Raymond Hettinger027bb632004-05-31 03:09:25 +000017from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000018import signal
Barry Warsawcf3d4b51997-01-03 20:03:32 +000019
Benjamin Petersonee8712c2008-05-20 21:35:26 +000020HOST = support.HOST
Guido van Rossum7d0a8262007-05-21 23:13:11 +000021MSG = b'Michael Gilfix was here\n'
Barry Warsawcf3d4b51997-01-03 20:03:32 +000022
Guido van Rossum24e4af82002-06-12 19:18:08 +000023class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000024
Guido van Rossum24e4af82002-06-12 19:18:08 +000025 def setUp(self):
26 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000027 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000028 self.serv.listen(1)
Barry Warsawcf3d4b51997-01-03 20:03:32 +000029
Guido van Rossum24e4af82002-06-12 19:18:08 +000030 def tearDown(self):
31 self.serv.close()
32 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000033
Guido van Rossum24e4af82002-06-12 19:18:08 +000034class SocketUDPTest(unittest.TestCase):
35
36 def setUp(self):
37 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000038 self.port = support.bind_port(self.serv)
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()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000100 self.queue = queue.Queue(1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000101
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()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000111 if not self.server_ready.is_set():
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000112 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
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000119 if self.queue.qsize():
Guido van Rossum24e4af82002-06-12 19:18:08 +0000120 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)
Christian Heimes5e696852008-04-09 08:37:03 +0000190 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000191 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)
Georg Brandlab91fde2009-08-13 08:51:18 +0000227 self.assertTrue(repr(s).startswith("<socket.socket object"))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000228
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
Georg Brandlab91fde2009-08-13 08:51:18 +0000250 self.assertRaises(socket.error, raise_error,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000251 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000252 self.assertRaises(socket.error, raise_herror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000253 "Error raising socket exception.")
Georg Brandlab91fde2009-08-13 08:51:18 +0000254 self.assertRaises(socket.error, raise_gaierror,
Guido van Rossum24e4af82002-06-12 19:18:08 +0000255 "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
Georg Brandlab91fde2009-08-13 08:51:18 +0000276 self.assertTrue(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 Rossum284a2cf2002-06-12 21:19:40 +0000289 if hasattr(sys, "getrefcount"):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000290 try:
291 # On some versions, this loses a reference
292 orig = sys.getrefcount(__name__)
293 socket.getnameinfo(__name__,0)
Benjamin Petersonf3d7dbe2009-10-04 14:54:52 +0000294 except TypeError:
Guido van Rossumb053cd82006-08-24 03:53:23 +0000295 if sys.getrefcount(__name__) != orig:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000296 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000297
Guido van Rossum24e4af82002-06-12 19:18:08 +0000298 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000299 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000300 try:
301 # On some versions, this crashes the interpreter.
302 socket.getnameinfo(('x', 0, 0, 0), 0)
303 except socket.error:
304 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000305
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000306 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000307 # This just checks that htons etc. are their own inverse,
308 # when looking at the lower 16 or 32 bits.
309 sizes = {socket.htonl: 32, socket.ntohl: 32,
310 socket.htons: 16, socket.ntohs: 16}
311 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000312 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000313 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
314 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000315
Guido van Rossuma2627af2002-09-14 00:58:46 +0000316 swapped = func(mask)
317 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000318 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000319
Guido van Rossum018919a2007-01-15 00:07:32 +0000320 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000321 good_values = [ 1, 2, 3, 1, 2, 3 ]
322 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000323 for k in good_values:
324 socket.ntohl(k)
325 socket.ntohs(k)
326 socket.htonl(k)
327 socket.htons(k)
328 for k in bad_values:
329 self.assertRaises(OverflowError, socket.ntohl, k)
330 self.assertRaises(OverflowError, socket.ntohs, k)
331 self.assertRaises(OverflowError, socket.htonl, k)
332 self.assertRaises(OverflowError, socket.htons, k)
333
Barry Warsaw11b91a02004-06-28 00:50:43 +0000334 def testGetServBy(self):
335 eq = self.assertEqual
336 # Find one service that exists, then check all the related interfaces.
337 # I've ordered this by protocols that have both a tcp and udp
338 # protocol, at least for modern Linuxes.
Brett Cannon08febeb2004-11-20 21:10:07 +0000339 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000340 'freebsd7', 'freebsd8', 'darwin'):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000341 # avoid the 'echo' service on this platform, as there is an
342 # assumption breaking non-standard port/protocol entry
343 services = ('daytime', 'qotd', 'domain')
344 else:
345 services = ('echo', 'daytime', 'domain')
346 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000347 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000348 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000349 break
350 except socket.error:
351 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000352 else:
353 raise socket.error
Barry Warsaw11b91a02004-06-28 00:50:43 +0000354 # Try same call with optional protocol omitted
355 port2 = socket.getservbyname(service)
356 eq(port, port2)
357 # Try udp, but don't barf it it doesn't exist
358 try:
359 udpport = socket.getservbyname(service, 'udp')
360 except socket.error:
361 udpport = None
362 else:
363 eq(udpport, port)
364 # Now make sure the lookup by port returns the same service name
365 eq(socket.getservbyport(port2), service)
366 eq(socket.getservbyport(port, 'tcp'), service)
367 if udpport is not None:
368 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000369 # Make sure getservbyport does not accept out of range ports.
370 self.assertRaises(OverflowError, socket.getservbyport, -1)
371 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000372
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000373 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000374 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000375 # The default timeout should initially be None
376 self.assertEqual(socket.getdefaulttimeout(), None)
377 s = socket.socket()
378 self.assertEqual(s.gettimeout(), None)
379 s.close()
380
381 # Set the default timeout to 10, and see if it propagates
382 socket.setdefaulttimeout(10)
383 self.assertEqual(socket.getdefaulttimeout(), 10)
384 s = socket.socket()
385 self.assertEqual(s.gettimeout(), 10)
386 s.close()
387
388 # Reset the default timeout to None, and see if it propagates
389 socket.setdefaulttimeout(None)
390 self.assertEqual(socket.getdefaulttimeout(), None)
391 s = socket.socket()
392 self.assertEqual(s.gettimeout(), None)
393 s.close()
394
395 # Check that setting it to an invalid value raises ValueError
396 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
397
398 # Check that setting it to an invalid type raises TypeError
399 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
400
Benjamin Petersonf91df042009-02-13 02:50:59 +0000401 def testIPv4_inet_aton_fourbytes(self):
402 if not hasattr(socket, 'inet_aton'):
403 return # No inet_aton, nothing to check
404 # Test that issue1008086 and issue767150 are fixed.
405 # It must return 4 bytes.
406 self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
407 self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
408
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000409 def testIPv4toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000410 if not hasattr(socket, 'inet_pton'):
411 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000412 from socket import inet_aton as f, inet_pton, AF_INET
413 g = lambda a: inet_pton(AF_INET, a)
414
Guido van Rossumb5b22702007-05-18 18:55:53 +0000415 self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
416 self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
417 self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
418 self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
419 self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000420
Guido van Rossumb5b22702007-05-18 18:55:53 +0000421 self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
422 self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
423 self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
424 self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000425
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000426 def testIPv6toString(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000427 if not hasattr(socket, 'inet_pton'):
428 return # No inet_pton() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000429 try:
430 from socket import inet_pton, AF_INET6, has_ipv6
431 if not has_ipv6:
432 return
433 except ImportError:
434 return
435 f = lambda a: inet_pton(AF_INET6, a)
436
Guido van Rossum540d9872007-08-17 03:51:09 +0000437 self.assertEquals(b'\x00' * 16, f('::'))
438 self.assertEquals(b'\x00' * 16, f('0::0'))
439 self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000440 self.assertEquals(
Guido van Rossum67180622007-07-10 07:29:12 +0000441 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 +0000442 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
443 )
Tim Petersc2659cf2003-05-12 20:19:37 +0000444
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000445 def testStringToIPv4(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000446 if not hasattr(socket, 'inet_ntop'):
447 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000448 from socket import inet_ntoa as f, inet_ntop, AF_INET
449 g = lambda a: inet_ntop(AF_INET, a)
450
Guido van Rossumb5b22702007-05-18 18:55:53 +0000451 self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
452 self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
453 self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
454 self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
Tim Petersc2659cf2003-05-12 20:19:37 +0000455
Guido van Rossumb5b22702007-05-18 18:55:53 +0000456 self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
457 self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
458 self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000459
460 def testStringToIPv6(self):
Guido van Rossumf4001ee2003-04-25 15:11:23 +0000461 if not hasattr(socket, 'inet_ntop'):
462 return # No inet_ntop() on this platform
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000463 try:
464 from socket import inet_ntop, AF_INET6, has_ipv6
465 if not has_ipv6:
466 return
467 except ImportError:
468 return
469 f = lambda a: inet_ntop(AF_INET6, a)
470
Guido van Rossum540d9872007-08-17 03:51:09 +0000471 self.assertEquals('::', f(b'\x00' * 16))
472 self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000473 self.assertEquals(
474 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +0000475 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 +0000476 )
477
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000478 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000479
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000480 def _get_unused_port(self, bind_address='0.0.0.0'):
481 """Use a temporary socket to elicit an unused ephemeral port.
Christian Heimes5e696852008-04-09 08:37:03 +0000482
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000483 Args:
484 bind_address: Hostname or IP address to search for a port on.
485
486 Returns: A most likely to be unused port.
487 """
488 tempsock = socket.socket()
489 tempsock.bind((bind_address, 0))
490 host, port = tempsock.getsockname()
491 tempsock.close()
492 return port
493
494 def testSockName(self):
495 # Testing getsockname()
496 port = self._get_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000497 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Christian Heimes5e696852008-04-09 08:37:03 +0000498 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000499 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000500 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
501 # it reasonable to get the host's addr in addition to 0.0.0.0.
502 # At least for eCos. This is required for the S/390 to pass.
503 my_ip_addr = socket.gethostbyname(socket.gethostname())
Georg Brandlab91fde2009-08-13 08:51:18 +0000504 self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +0000505 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000506
507 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000508 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000509 # We know a socket should start without reuse==0
510 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
511 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000512 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000513
514 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000515 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000516 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
517 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
518 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Georg Brandlab91fde2009-08-13 08:51:18 +0000519 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000520
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000521 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000522 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000523 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
524 sock.settimeout(1)
525 sock.close()
Guido van Rossum8a392d72007-11-21 22:09:45 +0000526 self.assertRaises(socket.error, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000527
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 def testNewAttributes(self):
529 # testing .family, .type and .protocol
530 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
531 self.assertEqual(sock.family, socket.AF_INET)
532 self.assertEqual(sock.type, socket.SOCK_STREAM)
533 self.assertEqual(sock.proto, 0)
534 sock.close()
535
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000536 def test_getsockaddrarg(self):
537 host = '0.0.0.0'
538 port = self._get_unused_port(bind_address=host)
539 big_port = port + 65536
540 neg_port = port - 65536
541 sock = socket.socket()
542 try:
543 self.assertRaises(OverflowError, sock.bind, (host, big_port))
544 self.assertRaises(OverflowError, sock.bind, (host, neg_port))
545 sock.bind((host, port))
546 finally:
547 sock.close()
548
Christian Heimesfaf2f632008-01-06 16:59:19 +0000549 def test_sock_ioctl(self):
550 if os.name != "nt":
551 return
Georg Brandlab91fde2009-08-13 08:51:18 +0000552 self.assertTrue(hasattr(socket.socket, 'ioctl'))
553 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
554 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
555 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Christian Heimesfaf2f632008-01-06 16:59:19 +0000556
557
Guido van Rossum24e4af82002-06-12 19:18:08 +0000558class BasicTCPTest(SocketConnectedTest):
559
560 def __init__(self, methodName='runTest'):
561 SocketConnectedTest.__init__(self, methodName=methodName)
562
563 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000564 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000565 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000566 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000567
568 def _testRecv(self):
569 self.serv_conn.send(MSG)
570
571 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000572 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000573 seg1 = self.cli_conn.recv(len(MSG) - 3)
574 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000575 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000576 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000577
578 def _testOverFlowRecv(self):
579 self.serv_conn.send(MSG)
580
581 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000582 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000583 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000584 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000585
586 def _testRecvFrom(self):
587 self.serv_conn.send(MSG)
588
589 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000590 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000591 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
592 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +0000593 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +0000594 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000595
596 def _testOverFlowRecvFrom(self):
597 self.serv_conn.send(MSG)
598
599 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000600 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000601 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000602 while 1:
603 read = self.cli_conn.recv(1024)
604 if not read:
605 break
Guido van Rossume531e292002-08-08 20:28:34 +0000606 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000607 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000608
609 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000610 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +0000611 self.serv_conn.sendall(big_chunk)
612
613 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000614 # Testing fromfd()
Guido van Rossum8e95ca82002-06-12 20:55:17 +0000615 if not hasattr(socket, "fromfd"):
Guido van Rossum6fb3d5e2002-06-12 20:48:59 +0000616 return # On Windows, this doesn't exist
Guido van Rossum24e4af82002-06-12 19:18:08 +0000617 fd = self.cli_conn.fileno()
618 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
619 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000620 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000621
622 def _testFromFd(self):
623 self.serv_conn.send(MSG)
624
Guido van Rossum39eb8fa2007-11-16 01:24:05 +0000625 def testDup(self):
626 # Testing dup()
627 sock = self.cli_conn.dup()
628 msg = sock.recv(1024)
629 self.assertEqual(msg, MSG)
630
631 def _testDup(self):
632 self.serv_conn.send(MSG)
633
Guido van Rossum24e4af82002-06-12 19:18:08 +0000634 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000635 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000636 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +0000637 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +0000638 # wait for _testShutdown to finish: on OS X, when the server
639 # closes the connection the client also becomes disconnected,
640 # and the client's shutdown call will fail. (Issue #4397.)
641 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000642
643 def _testShutdown(self):
644 self.serv_conn.send(MSG)
645 self.serv_conn.shutdown(2)
646
647class BasicUDPTest(ThreadedUDPSocketTest):
648
649 def __init__(self, methodName='runTest'):
650 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
651
652 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000653 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000654 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000655 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000656
657 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000658 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000659
Guido van Rossum1c938012002-06-12 21:17:20 +0000660 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000661 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +0000662 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000663 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000664
Guido van Rossum1c938012002-06-12 21:17:20 +0000665 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000666 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000667
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668 def testRecvFromNegative(self):
669 # Negative lengths passed to recvfrom should give ValueError.
670 self.assertRaises(ValueError, self.serv.recvfrom, -1)
671
672 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000673 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000675class TCPCloserTest(ThreadedTCPSocketTest):
676
677 def testClose(self):
678 conn, addr = self.serv.accept()
679 conn.close()
680
681 sd = self.cli
682 read, write, err = select.select([sd], [], [], 1.0)
683 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000684 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000685
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000686 # Calling close() many times should be safe.
687 conn.close()
688 conn.close()
689
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000690 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000691 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000692 time.sleep(1.0)
693
Dave Cole331708b2004-08-09 04:51:41 +0000694class BasicSocketPairTest(SocketPairTest):
695
696 def __init__(self, methodName='runTest'):
697 SocketPairTest.__init__(self, methodName=methodName)
698
699 def testRecv(self):
700 msg = self.serv.recv(1024)
701 self.assertEqual(msg, MSG)
702
703 def _testRecv(self):
704 self.cli.send(MSG)
705
706 def testSend(self):
707 self.serv.send(MSG)
708
709 def _testSend(self):
710 msg = self.cli.recv(1024)
711 self.assertEqual(msg, MSG)
712
Guido van Rossum24e4af82002-06-12 19:18:08 +0000713class NonBlockingTCPTests(ThreadedTCPSocketTest):
714
715 def __init__(self, methodName='runTest'):
716 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
717
718 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000719 # Testing whether set blocking works
Guido van Rossum24e4af82002-06-12 19:18:08 +0000720 self.serv.setblocking(0)
721 start = time.time()
722 try:
723 self.serv.accept()
724 except socket.error:
725 pass
726 end = time.time()
Georg Brandlab91fde2009-08-13 08:51:18 +0000727 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000728
729 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +0000730 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000731
Guido van Rossum24e4af82002-06-12 19:18:08 +0000732 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000733 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +0000734 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +0000735 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000736 conn, addr = self.serv.accept()
737 except socket.error:
738 pass
739 else:
740 self.fail("Error trying to do non-blocking accept.")
741 read, write, err = select.select([self.serv], [], [])
742 if self.serv in read:
743 conn, addr = self.serv.accept()
744 else:
745 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +0000746
Guido van Rossum24e4af82002-06-12 19:18:08 +0000747 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000748 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +0000749 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000750
751 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000752 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +0000753 conn, addr = self.serv.accept()
754
755 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +0000756 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +0000757 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000758
759 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000760 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +0000761 conn, addr = self.serv.accept()
762 conn.setblocking(0)
763 try:
764 msg = conn.recv(len(MSG))
765 except socket.error:
766 pass
767 else:
768 self.fail("Error trying to do non-blocking recv.")
769 read, write, err = select.select([conn], [], [])
770 if conn in read:
771 msg = conn.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +0000772 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000773 else:
774 self.fail("Error during select call to non-blocking socket.")
775
776 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000777 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +0000778 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000779 self.cli.send(MSG)
780
781class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000782 """Unit tests for the object returned by socket.makefile()
783
784 self.serv_file is the io object returned by makefile() on
785 the client connection. You can read from this file to
786 get output from the server.
787
788 self.cli_file is the io object returned by makefile() on the
789 server connection. You can write to this file to send output
790 to the client.
791 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000792
Guido van Rossume9f66142002-08-07 15:46:19 +0000793 bufsize = -1 # Use default buffer size
794
Guido van Rossum24e4af82002-06-12 19:18:08 +0000795 def __init__(self, methodName='runTest'):
796 SocketConnectedTest.__init__(self, methodName=methodName)
797
798 def setUp(self):
799 SocketConnectedTest.setUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000800 self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000801
802 def tearDown(self):
803 self.serv_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000804 self.assertTrue(self.serv_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000805 self.serv_file = None
806 SocketConnectedTest.tearDown(self)
807
808 def clientSetUp(self):
809 SocketConnectedTest.clientSetUp(self)
Guido van Rossume9f66142002-08-07 15:46:19 +0000810 self.cli_file = self.serv_conn.makefile('wb')
Guido van Rossum24e4af82002-06-12 19:18:08 +0000811
812 def clientTearDown(self):
813 self.cli_file.close()
Georg Brandlab91fde2009-08-13 08:51:18 +0000814 self.assertTrue(self.cli_file.closed)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000815 self.cli_file = None
816 SocketConnectedTest.clientTearDown(self)
817
818 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000819 # Performing small file read test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000820 first_seg = self.serv_file.read(len(MSG)-3)
821 second_seg = self.serv_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +0000822 msg = first_seg + second_seg
Guido van Rossum76489682002-06-12 20:38:30 +0000823 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000824
825 def _testSmallRead(self):
826 self.cli_file.write(MSG)
827 self.cli_file.flush()
828
Guido van Rossum8c943832002-08-08 01:00:28 +0000829 def testFullRead(self):
830 # read until EOF
831 msg = self.serv_file.read()
832 self.assertEqual(msg, MSG)
833
834 def _testFullRead(self):
835 self.cli_file.write(MSG)
836 self.cli_file.close()
837
Guido van Rossum24e4af82002-06-12 19:18:08 +0000838 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000839 # Performing unbuffered file read test
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000840 buf = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +0000841 while 1:
842 char = self.serv_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +0000843 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000844 break
Guido van Rossum8c943832002-08-08 01:00:28 +0000845 buf += char
846 self.assertEqual(buf, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000847
848 def _testUnbufferedRead(self):
849 self.cli_file.write(MSG)
850 self.cli_file.flush()
851
852 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000853 # Performing file readline test
Guido van Rossum24e4af82002-06-12 19:18:08 +0000854 line = self.serv_file.readline()
Guido van Rossum76489682002-06-12 20:38:30 +0000855 self.assertEqual(line, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000856
857 def _testReadline(self):
858 self.cli_file.write(MSG)
859 self.cli_file.flush()
860
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000861 def testCloseAfterMakefile(self):
862 # The file returned by makefile should keep the socket open.
863 self.cli_conn.close()
864 # read until EOF
865 msg = self.serv_file.read()
866 self.assertEqual(msg, MSG)
867
868 def _testCloseAfterMakefile(self):
869 self.cli_file.write(MSG)
870 self.cli_file.flush()
871
872 def testMakefileAfterMakefileClose(self):
873 self.serv_file.close()
874 msg = self.cli_conn.recv(len(MSG))
875 self.assertEqual(msg, MSG)
876
877 def _testMakefileAfterMakefileClose(self):
878 self.cli_file.write(MSG)
879 self.cli_file.flush()
880
Tim Peters116d83c2004-03-28 02:20:45 +0000881 def testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000882 self.assertTrue(not self.serv_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000883
884 def _testClosedAttr(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000885 self.assertTrue(not self.cli_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +0000886
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000887 def testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000888 self.assertEqual(self.serv_file.mode, 'rb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000889 self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
890
891 def _testAttributes(self):
Benjamin Peterson44309e62008-11-22 00:41:45 +0000892 self.assertEqual(self.cli_file.mode, 'wb')
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +0000893 self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
894
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000895 def testRealClose(self):
896 self.serv_file.close()
897 self.assertRaises(ValueError, self.serv_file.fileno)
898 self.cli_conn.close()
899 self.assertRaises(socket.error, self.cli_conn.getsockname)
900
901 def _testRealClose(self):
902 pass
903
904
Guido van Rossume9f66142002-08-07 15:46:19 +0000905class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
906
907 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +0000908
Guido van Rossume9f66142002-08-07 15:46:19 +0000909 In this case (and in this case only), it should be possible to
910 create a file object, read a line from it, create another file
911 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +0000912 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +0000913 when reading multiple requests from the same socket."""
914
915 bufsize = 0 # Use unbuffered mode
916
917 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000918 # Read a line, create a new file object, read another line with it
Guido van Rossume9f66142002-08-07 15:46:19 +0000919 line = self.serv_file.readline() # first line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000920 self.assertEqual(line, b"A. " + MSG) # first line
Guido van Rossume9f66142002-08-07 15:46:19 +0000921 self.serv_file = self.cli_conn.makefile('rb', 0)
922 line = self.serv_file.readline() # second line
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000923 self.assertEqual(line, b"B. " + MSG) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +0000924
925 def _testUnbufferedReadline(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000926 self.cli_file.write(b"A. " + MSG)
927 self.cli_file.write(b"B. " + MSG)
Guido van Rossume9f66142002-08-07 15:46:19 +0000928 self.cli_file.flush()
929
Gregory P. Smithde3369f2009-01-12 04:50:11 +0000930 def testMakefileClose(self):
931 # The file returned by makefile should keep the socket open...
932 self.cli_conn.close()
933 msg = self.cli_conn.recv(1024)
934 self.assertEqual(msg, MSG)
935 # ...until the file is itself closed
936 self.serv_file.close()
937 self.assertRaises(socket.error, self.cli_conn.recv, 1024)
938
939 def _testMakefileClose(self):
940 self.cli_file.write(MSG)
941 self.cli_file.flush()
942
943 def testMakefileCloseSocketDestroy(self):
944 refcount_before = sys.getrefcount(self.cli_conn)
945 self.serv_file.close()
946 refcount_after = sys.getrefcount(self.cli_conn)
947 self.assertEqual(refcount_before - 1, refcount_after)
948
949 def _testMakefileCloseSocketDestroy(self):
950 pass
951
952
Guido van Rossum8c943832002-08-08 01:00:28 +0000953class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
954
955 bufsize = 1 # Default-buffered for reading; line-buffered for writing
956
957
958class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
959
960 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +0000961
Thomas Woutersb2137042007-02-01 18:02:27 +0000962
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963class NetworkConnectionTest(object):
964 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000965
Guido van Rossumd8faa362007-04-27 19:54:29 +0000966 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +0000967 # We're inherited below by BasicTCPTest2, which also inherits
968 # BasicTCPTest, which defines self.port referenced below.
969 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970 self.serv_conn = self.cli
971
972class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
973 """Tests that NetworkConnection does not break existing TCP functionality.
974 """
975
976class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000977
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978 def testWithoutServer(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000979 port = support.find_unused_port()
Georg Brandlab91fde2009-08-13 08:51:18 +0000980 self.assertRaises(
Christian Heimes5e696852008-04-09 08:37:03 +0000981 socket.error,
982 lambda: socket.create_connection((HOST, port))
983 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984
985class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
986
987 def __init__(self, methodName='runTest'):
988 SocketTCPTest.__init__(self, methodName=methodName)
989 ThreadableTest.__init__(self)
990
991 def clientSetUp(self):
992 pass
993
994 def clientTearDown(self):
995 self.cli.close()
996 self.cli = None
997 ThreadableTest.clientTearDown(self)
998
999 def _justAccept(self):
1000 conn, addr = self.serv.accept()
1001
1002 testFamily = _justAccept
1003 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001004 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005 self.assertEqual(self.cli.family, 2)
1006
1007 testTimeoutDefault = _justAccept
1008 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001009 # passing no explicit timeout uses socket's global default
Georg Brandlab91fde2009-08-13 08:51:18 +00001010 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001011 socket.setdefaulttimeout(42)
1012 try:
1013 self.cli = socket.create_connection((HOST, self.port))
1014 finally:
1015 socket.setdefaulttimeout(None)
1016 self.assertEquals(self.cli.gettimeout(), 42)
1017
1018 testTimeoutNone = _justAccept
1019 def _testTimeoutNone(self):
1020 # None timeout means the same as sock.settimeout(None)
Georg Brandlab91fde2009-08-13 08:51:18 +00001021 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001022 socket.setdefaulttimeout(30)
1023 try:
1024 self.cli = socket.create_connection((HOST, self.port), timeout=None)
1025 finally:
1026 socket.setdefaulttimeout(None)
1027 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028
1029 testTimeoutValueNamed = _justAccept
1030 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001031 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032 self.assertEqual(self.cli.gettimeout(), 30)
1033
1034 testTimeoutValueNonamed = _justAccept
1035 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001036 self.cli = socket.create_connection((HOST, self.port), 30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037 self.assertEqual(self.cli.gettimeout(), 30)
1038
Guido van Rossumd8faa362007-04-27 19:54:29 +00001039class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1040
1041 def __init__(self, methodName='runTest'):
1042 SocketTCPTest.__init__(self, methodName=methodName)
1043 ThreadableTest.__init__(self)
1044
1045 def clientSetUp(self):
1046 pass
1047
1048 def clientTearDown(self):
1049 self.cli.close()
1050 self.cli = None
1051 ThreadableTest.clientTearDown(self)
1052
1053 def testInsideTimeout(self):
1054 conn, addr = self.serv.accept()
1055 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001056 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 testOutsideTimeout = testInsideTimeout
1058
1059 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001060 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001061 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001062 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063
1064 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001065 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00001066 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067
1068
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001069class TCPTimeoutTest(SocketTCPTest):
1070
1071 def testTCPTimeout(self):
1072 def raise_timeout(*args, **kwargs):
1073 self.serv.settimeout(1.0)
1074 self.serv.accept()
Georg Brandlab91fde2009-08-13 08:51:18 +00001075 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001076 "Error generating a timeout exception (TCP)")
1077
1078 def testTimeoutZero(self):
1079 ok = False
1080 try:
1081 self.serv.settimeout(0.0)
1082 foo = self.serv.accept()
1083 except socket.timeout:
1084 self.fail("caught timeout instead of error (TCP)")
1085 except socket.error:
1086 ok = True
1087 except:
1088 self.fail("caught unexpected exception (TCP)")
1089 if not ok:
1090 self.fail("accept() returned success when we did not expect it")
1091
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001092 def testInterruptedTimeout(self):
1093 # XXX I don't know how to do this test on MSWindows or any other
1094 # plaform that doesn't support signal.alarm() or os.kill(), though
1095 # the bug should have existed on all platforms.
1096 if not hasattr(signal, "alarm"):
1097 return # can only test on *nix
1098 self.serv.settimeout(5.0) # must be longer than alarm
1099 class Alarm(Exception):
1100 pass
1101 def alarm_handler(signal, frame):
1102 raise Alarm
1103 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1104 try:
1105 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
1106 try:
1107 foo = self.serv.accept()
1108 except socket.timeout:
1109 self.fail("caught timeout instead of Alarm")
1110 except Alarm:
1111 pass
1112 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001113 self.fail("caught other exception instead of Alarm:"
1114 " %s(%s):\n%s" %
1115 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116 else:
1117 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00001118 finally:
1119 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120 except Alarm:
1121 self.fail("got Alarm in wrong place")
1122 finally:
1123 # no alarm can be pending. Safe to restore old handler.
1124 signal.signal(signal.SIGALRM, old_alarm)
1125
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001126class UDPTimeoutTest(SocketTCPTest):
1127
1128 def testUDPTimeout(self):
1129 def raise_timeout(*args, **kwargs):
1130 self.serv.settimeout(1.0)
1131 self.serv.recv(1024)
Georg Brandlab91fde2009-08-13 08:51:18 +00001132 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001133 "Error generating a timeout exception (UDP)")
1134
1135 def testTimeoutZero(self):
1136 ok = False
1137 try:
1138 self.serv.settimeout(0.0)
1139 foo = self.serv.recv(1024)
1140 except socket.timeout:
1141 self.fail("caught timeout instead of error (UDP)")
1142 except socket.error:
1143 ok = True
1144 except:
1145 self.fail("caught unexpected exception (UDP)")
1146 if not ok:
1147 self.fail("recv() returned success when we did not expect it")
1148
1149class TestExceptions(unittest.TestCase):
1150
1151 def testExceptionTree(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001152 self.assertTrue(issubclass(socket.error, Exception))
1153 self.assertTrue(issubclass(socket.herror, socket.error))
1154 self.assertTrue(issubclass(socket.gaierror, socket.error))
1155 self.assertTrue(issubclass(socket.timeout, socket.error))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001156
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001157class TestLinuxAbstractNamespace(unittest.TestCase):
1158
1159 UNIX_PATH_MAX = 108
1160
1161 def testLinuxAbstractNamespace(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001162 address = b"\x00python-test-hello\x00\xff"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001163 s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1164 s1.bind(address)
1165 s1.listen(1)
1166 s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1167 s2.connect(s1.getsockname())
1168 s1.accept()
1169 self.assertEqual(s1.getsockname(), address)
1170 self.assertEqual(s2.getpeername(), address)
1171
1172 def testMaxName(self):
Guido van Rossum32c4ac02007-08-15 03:56:40 +00001173 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001174 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1175 s.bind(address)
1176 self.assertEqual(s.getsockname(), address)
1177
1178 def testNameOverflow(self):
1179 address = "\x00" + "h" * self.UNIX_PATH_MAX
1180 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1181 self.assertRaises(socket.error, s.bind, address)
1182
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001183
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184class BufferIOTest(SocketConnectedTest):
1185 """
1186 Test the buffer versions of socket.recv() and socket.send().
1187 """
1188 def __init__(self, methodName='runTest'):
1189 SocketConnectedTest.__init__(self, methodName=methodName)
1190
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001191 def testRecvInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001192 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001193 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001195 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001196 self.assertEqual(msg, MSG)
1197
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001198 def _testRecvInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001199 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 self.serv_conn.send(buf)
1201
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001202 def testRecvFromInto(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00001203 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001204 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001205 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001206 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001207 self.assertEqual(msg, MSG)
1208
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001209 def _testRecvFromInto(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00001210 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001211 self.serv_conn.send(buf)
1212
Christian Heimes043d6f62008-01-07 17:19:16 +00001213
1214TIPC_STYPE = 2000
1215TIPC_LOWER = 200
1216TIPC_UPPER = 210
1217
1218def isTipcAvailable():
1219 """Check if the TIPC module is loaded
1220
1221 The TIPC module is not loaded automatically on Ubuntu and probably
1222 other Linux distros.
1223 """
1224 if not hasattr(socket, "AF_TIPC"):
1225 return False
1226 if not os.path.isfile("/proc/modules"):
1227 return False
1228 with open("/proc/modules") as f:
1229 for line in f:
1230 if line.startswith("tipc "):
1231 return True
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001232 if support.verbose:
Christian Heimes043d6f62008-01-07 17:19:16 +00001233 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1234 return False
1235
1236class TIPCTest (unittest.TestCase):
1237 def testRDM(self):
1238 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1239 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1240
1241 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1242 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1243 TIPC_LOWER, TIPC_UPPER)
1244 srv.bind(srvaddr)
1245
1246 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1247 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1248 cli.sendto(MSG, sendaddr)
1249
1250 msg, recvaddr = srv.recvfrom(1024)
1251
1252 self.assertEqual(cli.getsockname(), recvaddr)
1253 self.assertEqual(msg, MSG)
1254
1255
1256class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1257 def __init__(self, methodName = 'runTest'):
1258 unittest.TestCase.__init__(self, methodName = methodName)
1259 ThreadableTest.__init__(self)
1260
1261 def setUp(self):
1262 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1263 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1264 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1265 TIPC_LOWER, TIPC_UPPER)
1266 self.srv.bind(srvaddr)
1267 self.srv.listen(5)
1268 self.serverExplicitReady()
1269 self.conn, self.connaddr = self.srv.accept()
1270
1271 def clientSetUp(self):
1272 # The is a hittable race between serverExplicitReady() and the
1273 # accept() call; sleep a little while to avoid it, otherwise
1274 # we could get an exception
1275 time.sleep(0.1)
1276 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1277 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1278 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1279 self.cli.connect(addr)
1280 self.cliaddr = self.cli.getsockname()
1281
1282 def testStream(self):
1283 msg = self.conn.recv(1024)
1284 self.assertEqual(msg, MSG)
1285 self.assertEqual(self.cliaddr, self.connaddr)
1286
1287 def _testStream(self):
1288 self.cli.send(MSG)
1289 self.cli.close()
1290
1291
Guido van Rossumb995eb72002-07-31 16:08:40 +00001292def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001294 TestExceptions, BufferIOTest, BasicTCPTest2]
Jack Jansen522e7692002-09-06 21:57:50 +00001295 if sys.platform != 'mac':
Raymond Hettinger11a35f52003-06-29 04:40:22 +00001296 tests.extend([ BasicUDPTest, UDPTimeoutTest ])
Walter Dörwald21d3a322003-05-01 17:45:56 +00001297
1298 tests.extend([
1299 NonBlockingTCPTests,
1300 FileObjectClassTestCase,
1301 UnbufferedFileObjectClassTestCase,
1302 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00001303 SmallBufferedFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001304 NetworkConnectionNoServer,
1305 NetworkConnectionAttributesTest,
1306 NetworkConnectionBehaviourTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001307 ])
Dave Cole331708b2004-08-09 04:51:41 +00001308 if hasattr(socket, "socketpair"):
1309 tests.append(BasicSocketPairTest)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001310 if sys.platform == 'linux2':
1311 tests.append(TestLinuxAbstractNamespace)
Christian Heimes043d6f62008-01-07 17:19:16 +00001312 if isTipcAvailable():
1313 tests.append(TIPCTest)
Christian Heimes790c8232008-01-07 21:14:23 +00001314 tests.append(TIPCThreadableTest)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001315
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001316 thread_info = support.threading_setup()
1317 support.run_unittest(*tests)
1318 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001319
1320if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00001321 test_main()