Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 3 | import unittest |
Barry Warsaw | 04f357c | 2002-07-23 19:04:11 +0000 | [diff] [blame] | 4 | from test import test_support |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 5 | |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 6 | import errno |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 7 | import socket |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 8 | import select |
Jeffrey Yasskin | 36550bd | 2008-03-28 04:53:10 +0000 | [diff] [blame] | 9 | import time |
| 10 | import traceback |
Georg Brandl | a6168f9 | 2008-05-25 07:20:14 +0000 | [diff] [blame] | 11 | import Queue |
Jack Jansen | 522e769 | 2002-09-06 21:57:50 +0000 | [diff] [blame] | 12 | import sys |
Christian Heimes | a47b75b | 2008-01-04 15:48:06 +0000 | [diff] [blame] | 13 | import os |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 14 | import array |
Antoine Pitrou | c818ed4 | 2010-09-07 21:40:25 +0000 | [diff] [blame] | 15 | import contextlib |
Raymond Hettinger | 027bb63 | 2004-05-31 03:09:25 +0000 | [diff] [blame] | 16 | from weakref import proxy |
Neal Norwitz | 9b0ca79 | 2006-08-02 06:46:21 +0000 | [diff] [blame] | 17 | import signal |
Antoine Pitrou | 66b5df6 | 2010-09-27 18:16:46 +0000 | [diff] [blame] | 18 | import math |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 19 | |
Giampaolo Rodolà | 633e474 | 2010-08-14 17:04:46 +0000 | [diff] [blame] | 20 | def try_address(host, port=0, family=socket.AF_INET): |
| 21 | """Try to bind a socket on the given host:port and return True |
| 22 | if that has been possible.""" |
| 23 | try: |
| 24 | sock = socket.socket(family, socket.SOCK_STREAM) |
| 25 | sock.bind((host, port)) |
| 26 | except (socket.error, socket.gaierror): |
| 27 | return False |
| 28 | else: |
| 29 | sock.close() |
| 30 | return True |
| 31 | |
| 32 | HOST = test_support.HOST |
| 33 | MSG = b'Michael Gilfix was here\n' |
| 34 | SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6) |
| 35 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 36 | try: |
| 37 | import thread |
| 38 | import threading |
| 39 | except ImportError: |
| 40 | thread = None |
| 41 | threading = None |
| 42 | |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 43 | HOST = test_support.HOST |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 44 | MSG = 'Michael Gilfix was here\n' |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 45 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 46 | class SocketTCPTest(unittest.TestCase): |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 47 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 48 | def setUp(self): |
| 49 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 50 | self.port = test_support.bind_port(self.serv) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 51 | self.serv.listen(1) |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 52 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 53 | def tearDown(self): |
| 54 | self.serv.close() |
| 55 | self.serv = None |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 56 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 57 | class SocketUDPTest(unittest.TestCase): |
| 58 | |
| 59 | def setUp(self): |
| 60 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 61 | self.port = test_support.bind_port(self.serv) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 62 | |
| 63 | def tearDown(self): |
| 64 | self.serv.close() |
| 65 | self.serv = None |
| 66 | |
| 67 | class ThreadableTest: |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 68 | """Threadable Test class |
| 69 | |
| 70 | The ThreadableTest class makes it easy to create a threaded |
| 71 | client/server pair from an existing unit test. To create a |
| 72 | new threaded class from an existing unit test, use multiple |
| 73 | inheritance: |
| 74 | |
| 75 | class NewClass (OldClass, ThreadableTest): |
| 76 | pass |
| 77 | |
| 78 | This class defines two new fixture functions with obvious |
| 79 | purposes for overriding: |
| 80 | |
| 81 | clientSetUp () |
| 82 | clientTearDown () |
| 83 | |
| 84 | Any new test functions within the class must then define |
| 85 | tests in pairs, where the test name is preceeded with a |
| 86 | '_' to indicate the client portion of the test. Ex: |
| 87 | |
| 88 | def testFoo(self): |
| 89 | # Server portion |
| 90 | |
| 91 | def _testFoo(self): |
| 92 | # Client portion |
| 93 | |
| 94 | Any exceptions raised by the clients during their tests |
| 95 | are caught and transferred to the main thread to alert |
| 96 | the testing framework. |
| 97 | |
| 98 | Note, the server setup function cannot call any blocking |
| 99 | functions that rely on the client thread during setup, |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 100 | unless serverExplicitReady() is called just before |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 101 | the blocking call (such as in setting up a client/server |
| 102 | connection and performing the accept() in setUp(). |
| 103 | """ |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 104 | |
| 105 | def __init__(self): |
| 106 | # Swap the true setup function |
| 107 | self.__setUp = self.setUp |
| 108 | self.__tearDown = self.tearDown |
| 109 | self.setUp = self._setUp |
| 110 | self.tearDown = self._tearDown |
| 111 | |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 112 | def serverExplicitReady(self): |
| 113 | """This method allows the server to explicitly indicate that |
| 114 | it wants the client thread to proceed. This is useful if the |
| 115 | server is about to execute a blocking routine that is |
| 116 | dependent upon the client thread during its setup routine.""" |
| 117 | self.server_ready.set() |
| 118 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 119 | def _setUp(self): |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 120 | self.server_ready = threading.Event() |
| 121 | self.client_ready = threading.Event() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 122 | self.done = threading.Event() |
Georg Brandl | a6168f9 | 2008-05-25 07:20:14 +0000 | [diff] [blame] | 123 | self.queue = Queue.Queue(1) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 124 | |
| 125 | # Do some munging to start the client test. |
Guido van Rossum | 11ba094 | 2002-06-13 15:07:44 +0000 | [diff] [blame] | 126 | methodname = self.id() |
| 127 | i = methodname.rfind('.') |
| 128 | methodname = methodname[i+1:] |
| 129 | test_method = getattr(self, '_' + methodname) |
Guido van Rossum | ab65996 | 2002-06-12 21:29:43 +0000 | [diff] [blame] | 130 | self.client_thread = thread.start_new_thread( |
| 131 | self.clientRun, (test_method,)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 132 | |
| 133 | self.__setUp() |
Benjamin Peterson | 0fbcf69 | 2008-06-11 17:27:50 +0000 | [diff] [blame] | 134 | if not self.server_ready.is_set(): |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 135 | self.server_ready.set() |
| 136 | self.client_ready.wait() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 137 | |
| 138 | def _tearDown(self): |
| 139 | self.__tearDown() |
| 140 | self.done.wait() |
| 141 | |
| 142 | if not self.queue.empty(): |
| 143 | msg = self.queue.get() |
| 144 | self.fail(msg) |
| 145 | |
| 146 | def clientRun(self, test_func): |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 147 | self.server_ready.wait() |
| 148 | self.client_ready.set() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 149 | self.clientSetUp() |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 150 | with test_support.check_py3k_warnings(): |
| 151 | if not callable(test_func): |
| 152 | raise TypeError("test_func must be a callable function.") |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 153 | try: |
| 154 | test_func() |
| 155 | except Exception, strerror: |
| 156 | self.queue.put(strerror) |
| 157 | self.clientTearDown() |
| 158 | |
| 159 | def clientSetUp(self): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 160 | raise NotImplementedError("clientSetUp must be implemented.") |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 161 | |
| 162 | def clientTearDown(self): |
| 163 | self.done.set() |
| 164 | thread.exit() |
| 165 | |
| 166 | class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): |
| 167 | |
| 168 | def __init__(self, methodName='runTest'): |
| 169 | SocketTCPTest.__init__(self, methodName=methodName) |
| 170 | ThreadableTest.__init__(self) |
| 171 | |
| 172 | def clientSetUp(self): |
| 173 | self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 174 | |
| 175 | def clientTearDown(self): |
| 176 | self.cli.close() |
| 177 | self.cli = None |
| 178 | ThreadableTest.clientTearDown(self) |
| 179 | |
| 180 | class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): |
| 181 | |
| 182 | def __init__(self, methodName='runTest'): |
| 183 | SocketUDPTest.__init__(self, methodName=methodName) |
| 184 | ThreadableTest.__init__(self) |
| 185 | |
| 186 | def clientSetUp(self): |
| 187 | self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 188 | |
| 189 | class SocketConnectedTest(ThreadedTCPSocketTest): |
| 190 | |
| 191 | def __init__(self, methodName='runTest'): |
| 192 | ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
| 193 | |
| 194 | def setUp(self): |
| 195 | ThreadedTCPSocketTest.setUp(self) |
Guido van Rossum | 83ccb4e | 2002-06-18 18:35:13 +0000 | [diff] [blame] | 196 | # Indicate explicitly we're ready for the client thread to |
| 197 | # proceed and then perform the blocking call to accept |
| 198 | self.serverExplicitReady() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 199 | conn, addr = self.serv.accept() |
| 200 | self.cli_conn = conn |
| 201 | |
| 202 | def tearDown(self): |
| 203 | self.cli_conn.close() |
| 204 | self.cli_conn = None |
| 205 | ThreadedTCPSocketTest.tearDown(self) |
| 206 | |
| 207 | def clientSetUp(self): |
| 208 | ThreadedTCPSocketTest.clientSetUp(self) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 209 | self.cli.connect((HOST, self.port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 210 | self.serv_conn = self.cli |
| 211 | |
| 212 | def clientTearDown(self): |
| 213 | self.serv_conn.close() |
| 214 | self.serv_conn = None |
| 215 | ThreadedTCPSocketTest.clientTearDown(self) |
| 216 | |
Dave Cole | 331708b | 2004-08-09 04:51:41 +0000 | [diff] [blame] | 217 | class SocketPairTest(unittest.TestCase, ThreadableTest): |
| 218 | |
| 219 | def __init__(self, methodName='runTest'): |
| 220 | unittest.TestCase.__init__(self, methodName=methodName) |
| 221 | ThreadableTest.__init__(self) |
| 222 | |
| 223 | def setUp(self): |
| 224 | self.serv, self.cli = socket.socketpair() |
| 225 | |
| 226 | def tearDown(self): |
| 227 | self.serv.close() |
| 228 | self.serv = None |
| 229 | |
| 230 | def clientSetUp(self): |
| 231 | pass |
| 232 | |
| 233 | def clientTearDown(self): |
| 234 | self.cli.close() |
| 235 | self.cli = None |
| 236 | ThreadableTest.clientTearDown(self) |
| 237 | |
Tim Peters | 494aaee | 2004-08-09 18:54:11 +0000 | [diff] [blame] | 238 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 239 | ####################################################################### |
| 240 | ## Begin Tests |
| 241 | |
| 242 | class GeneralModuleTests(unittest.TestCase): |
| 243 | |
Raymond Hettinger | 027bb63 | 2004-05-31 03:09:25 +0000 | [diff] [blame] | 244 | def test_weakref(self): |
| 245 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 246 | p = proxy(s) |
| 247 | self.assertEqual(p.fileno(), s.fileno()) |
| 248 | s.close() |
| 249 | s = None |
| 250 | try: |
| 251 | p.fileno() |
| 252 | except ReferenceError: |
| 253 | pass |
| 254 | else: |
| 255 | self.fail('Socket proxy still exists') |
| 256 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 257 | def testSocketError(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 258 | # Testing socket module exceptions |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 259 | def raise_error(*args, **kwargs): |
| 260 | raise socket.error |
| 261 | def raise_herror(*args, **kwargs): |
| 262 | raise socket.herror |
| 263 | def raise_gaierror(*args, **kwargs): |
| 264 | raise socket.gaierror |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 265 | self.assertRaises(socket.error, raise_error, |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 266 | "Error raising socket exception.") |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 267 | self.assertRaises(socket.error, raise_herror, |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 268 | "Error raising socket exception.") |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 269 | self.assertRaises(socket.error, raise_gaierror, |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 270 | "Error raising socket exception.") |
| 271 | |
| 272 | def testCrucialConstants(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 273 | # Testing for mission critical constants |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 274 | socket.AF_INET |
| 275 | socket.SOCK_STREAM |
| 276 | socket.SOCK_DGRAM |
| 277 | socket.SOCK_RAW |
| 278 | socket.SOCK_RDM |
| 279 | socket.SOCK_SEQPACKET |
| 280 | socket.SOL_SOCKET |
| 281 | socket.SO_REUSEADDR |
| 282 | |
Guido van Rossum | 654c11e | 2002-06-13 20:24:17 +0000 | [diff] [blame] | 283 | def testHostnameRes(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 284 | # Testing hostname resolution mechanisms |
Guido van Rossum | 654c11e | 2002-06-13 20:24:17 +0000 | [diff] [blame] | 285 | hostname = socket.gethostname() |
Guido van Rossum | 71e0294 | 2002-12-26 16:55:15 +0000 | [diff] [blame] | 286 | try: |
| 287 | ip = socket.gethostbyname(hostname) |
| 288 | except socket.error: |
| 289 | # Probably name lookup wasn't set up right; skip this test |
| 290 | return |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 291 | self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.") |
Guido van Rossum | 9647b52 | 2002-12-26 17:04:45 +0000 | [diff] [blame] | 292 | try: |
| 293 | hname, aliases, ipaddrs = socket.gethostbyaddr(ip) |
| 294 | except socket.error: |
| 295 | # Probably a similar problem as above; skip this test |
| 296 | return |
Brett Cannon | 01668a1 | 2005-03-11 00:04:17 +0000 | [diff] [blame] | 297 | all_host_names = [hostname, hname] + aliases |
Anthony Baxter | cf0a2a8 | 2006-04-03 08:10:33 +0000 | [diff] [blame] | 298 | fqhn = socket.getfqdn(ip) |
Guido van Rossum | 654c11e | 2002-06-13 20:24:17 +0000 | [diff] [blame] | 299 | if not fqhn in all_host_names: |
Martin v. Löwis | 04855cc | 2006-03-26 16:40:47 +0000 | [diff] [blame] | 300 | self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 301 | |
Guido van Rossum | 284a2cf | 2002-06-12 21:19:40 +0000 | [diff] [blame] | 302 | def testRefCountGetNameInfo(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 303 | # Testing reference count for getnameinfo |
Guido van Rossum | 284a2cf | 2002-06-12 21:19:40 +0000 | [diff] [blame] | 304 | if hasattr(sys, "getrefcount"): |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 305 | try: |
| 306 | # On some versions, this loses a reference |
| 307 | orig = sys.getrefcount(__name__) |
| 308 | socket.getnameinfo(__name__,0) |
Georg Brandl | ab84989 | 2009-09-19 07:35:07 +0000 | [diff] [blame] | 309 | except TypeError: |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 310 | self.assertEqual(sys.getrefcount(__name__), orig, |
| 311 | "socket.getnameinfo loses a reference") |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 312 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 313 | def testInterpreterCrash(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 314 | # Making sure getnameinfo doesn't crash the interpreter |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 315 | try: |
| 316 | # On some versions, this crashes the interpreter. |
| 317 | socket.getnameinfo(('x', 0, 0, 0), 0) |
| 318 | except socket.error: |
| 319 | pass |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 320 | |
Guido van Rossum | c0a0e08 | 2002-09-16 01:30:03 +0000 | [diff] [blame] | 321 | def testNtoH(self): |
Guido van Rossum | a2627af | 2002-09-14 00:58:46 +0000 | [diff] [blame] | 322 | # This just checks that htons etc. are their own inverse, |
| 323 | # when looking at the lower 16 or 32 bits. |
| 324 | sizes = {socket.htonl: 32, socket.ntohl: 32, |
| 325 | socket.htons: 16, socket.ntohs: 16} |
| 326 | for func, size in sizes.items(): |
| 327 | mask = (1L<<size) - 1 |
| 328 | for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): |
| 329 | self.assertEqual(i & mask, func(func(i&mask)) & mask) |
Jeremy Hylton | cbd5b89 | 2002-07-31 15:57:39 +0000 | [diff] [blame] | 330 | |
Guido van Rossum | a2627af | 2002-09-14 00:58:46 +0000 | [diff] [blame] | 331 | swapped = func(mask) |
| 332 | self.assertEqual(swapped & mask, mask) |
| 333 | self.assertRaises(OverflowError, func, 1L<<34) |
Jeremy Hylton | c075e19 | 2002-07-25 16:01:12 +0000 | [diff] [blame] | 334 | |
Guido van Rossum | bb2cc69 | 2007-01-14 17:03:32 +0000 | [diff] [blame] | 335 | def testNtoHErrors(self): |
| 336 | good_values = [ 1, 2, 3, 1L, 2L, 3L ] |
| 337 | bad_values = [ -1, -2, -3, -1L, -2L, -3L ] |
| 338 | for k in good_values: |
| 339 | socket.ntohl(k) |
| 340 | socket.ntohs(k) |
| 341 | socket.htonl(k) |
| 342 | socket.htons(k) |
| 343 | for k in bad_values: |
| 344 | self.assertRaises(OverflowError, socket.ntohl, k) |
| 345 | self.assertRaises(OverflowError, socket.ntohs, k) |
| 346 | self.assertRaises(OverflowError, socket.htonl, k) |
| 347 | self.assertRaises(OverflowError, socket.htons, k) |
| 348 | |
Barry Warsaw | 11b91a0 | 2004-06-28 00:50:43 +0000 | [diff] [blame] | 349 | def testGetServBy(self): |
| 350 | eq = self.assertEqual |
| 351 | # Find one service that exists, then check all the related interfaces. |
| 352 | # I've ordered this by protocols that have both a tcp and udp |
| 353 | # protocol, at least for modern Linuxes. |
Gregory P. Smith | 886a1cd | 2010-10-17 04:28:14 +0000 | [diff] [blame^] | 354 | if (sys.platform.startswith('linux') or |
| 355 | sys.platform.startswith('freebsd') or |
| 356 | sys.platform.startswith('netbsd') or |
| 357 | sys.platform == 'darwin'): |
Andrew MacIntyre | 18bf43c | 2004-07-12 12:10:30 +0000 | [diff] [blame] | 358 | # avoid the 'echo' service on this platform, as there is an |
| 359 | # assumption breaking non-standard port/protocol entry |
| 360 | services = ('daytime', 'qotd', 'domain') |
| 361 | else: |
| 362 | services = ('echo', 'daytime', 'domain') |
| 363 | for service in services: |
Skip Montanaro | f443330 | 2002-08-02 15:52:30 +0000 | [diff] [blame] | 364 | try: |
Barry Warsaw | 11b91a0 | 2004-06-28 00:50:43 +0000 | [diff] [blame] | 365 | port = socket.getservbyname(service, 'tcp') |
Skip Montanaro | f443330 | 2002-08-02 15:52:30 +0000 | [diff] [blame] | 366 | break |
| 367 | except socket.error: |
| 368 | pass |
Skip Montanaro | 05eb401 | 2004-02-10 15:51:15 +0000 | [diff] [blame] | 369 | else: |
| 370 | raise socket.error |
Barry Warsaw | 11b91a0 | 2004-06-28 00:50:43 +0000 | [diff] [blame] | 371 | # Try same call with optional protocol omitted |
| 372 | port2 = socket.getservbyname(service) |
| 373 | eq(port, port2) |
| 374 | # Try udp, but don't barf it it doesn't exist |
| 375 | try: |
| 376 | udpport = socket.getservbyname(service, 'udp') |
| 377 | except socket.error: |
| 378 | udpport = None |
| 379 | else: |
| 380 | eq(udpport, port) |
| 381 | # Now make sure the lookup by port returns the same service name |
| 382 | eq(socket.getservbyport(port2), service) |
| 383 | eq(socket.getservbyport(port, 'tcp'), service) |
| 384 | if udpport is not None: |
| 385 | eq(socket.getservbyport(udpport, 'udp'), service) |
Gregory P. Smith | de1a8b7 | 2009-01-31 22:57:30 +0000 | [diff] [blame] | 386 | # Make sure getservbyport does not accept out of range ports. |
| 387 | self.assertRaises(OverflowError, socket.getservbyport, -1) |
| 388 | self.assertRaises(OverflowError, socket.getservbyport, 65536) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 389 | |
Guido van Rossum | 9d0c8ce | 2002-07-18 17:08:35 +0000 | [diff] [blame] | 390 | def testDefaultTimeout(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 391 | # Testing default timeout |
Guido van Rossum | 9d0c8ce | 2002-07-18 17:08:35 +0000 | [diff] [blame] | 392 | # The default timeout should initially be None |
| 393 | self.assertEqual(socket.getdefaulttimeout(), None) |
| 394 | s = socket.socket() |
| 395 | self.assertEqual(s.gettimeout(), None) |
| 396 | s.close() |
| 397 | |
| 398 | # Set the default timeout to 10, and see if it propagates |
| 399 | socket.setdefaulttimeout(10) |
| 400 | self.assertEqual(socket.getdefaulttimeout(), 10) |
| 401 | s = socket.socket() |
| 402 | self.assertEqual(s.gettimeout(), 10) |
| 403 | s.close() |
| 404 | |
| 405 | # Reset the default timeout to None, and see if it propagates |
| 406 | socket.setdefaulttimeout(None) |
| 407 | self.assertEqual(socket.getdefaulttimeout(), None) |
| 408 | s = socket.socket() |
| 409 | self.assertEqual(s.gettimeout(), None) |
| 410 | s.close() |
| 411 | |
| 412 | # Check that setting it to an invalid value raises ValueError |
| 413 | self.assertRaises(ValueError, socket.setdefaulttimeout, -1) |
| 414 | |
| 415 | # Check that setting it to an invalid type raises TypeError |
| 416 | self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") |
| 417 | |
Gregory P. Smith | 3605b5c | 2009-02-11 23:45:25 +0000 | [diff] [blame] | 418 | def testIPv4_inet_aton_fourbytes(self): |
| 419 | if not hasattr(socket, 'inet_aton'): |
| 420 | return # No inet_aton, nothing to check |
| 421 | # Test that issue1008086 and issue767150 are fixed. |
| 422 | # It must return 4 bytes. |
| 423 | self.assertEquals('\x00'*4, socket.inet_aton('0.0.0.0')) |
| 424 | self.assertEquals('\xff'*4, socket.inet_aton('255.255.255.255')) |
| 425 | |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 426 | def testIPv4toString(self): |
Guido van Rossum | f4001ee | 2003-04-25 15:11:23 +0000 | [diff] [blame] | 427 | if not hasattr(socket, 'inet_pton'): |
| 428 | return # No inet_pton() on this platform |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 429 | from socket import inet_aton as f, inet_pton, AF_INET |
| 430 | g = lambda a: inet_pton(AF_INET, a) |
| 431 | |
| 432 | self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0')) |
| 433 | self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0')) |
| 434 | self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170')) |
| 435 | self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4')) |
Georg Brandl | d2e3ba7 | 2005-08-26 08:34:00 +0000 | [diff] [blame] | 436 | self.assertEquals('\xff\xff\xff\xff', f('255.255.255.255')) |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 437 | |
| 438 | self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0')) |
| 439 | self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0')) |
| 440 | self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170')) |
Georg Brandl | d2e3ba7 | 2005-08-26 08:34:00 +0000 | [diff] [blame] | 441 | self.assertEquals('\xff\xff\xff\xff', g('255.255.255.255')) |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 442 | |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 443 | def testIPv6toString(self): |
Guido van Rossum | f4001ee | 2003-04-25 15:11:23 +0000 | [diff] [blame] | 444 | if not hasattr(socket, 'inet_pton'): |
| 445 | return # No inet_pton() on this platform |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 446 | try: |
| 447 | from socket import inet_pton, AF_INET6, has_ipv6 |
| 448 | if not has_ipv6: |
| 449 | return |
| 450 | except ImportError: |
| 451 | return |
| 452 | f = lambda a: inet_pton(AF_INET6, a) |
| 453 | |
| 454 | self.assertEquals('\x00' * 16, f('::')) |
| 455 | self.assertEquals('\x00' * 16, f('0::0')) |
| 456 | self.assertEquals('\x00\x01' + '\x00' * 14, f('1::')) |
| 457 | self.assertEquals( |
| 458 | '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', |
| 459 | f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') |
| 460 | ) |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 461 | |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 462 | def testStringToIPv4(self): |
Guido van Rossum | f4001ee | 2003-04-25 15:11:23 +0000 | [diff] [blame] | 463 | if not hasattr(socket, 'inet_ntop'): |
| 464 | return # No inet_ntop() on this platform |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 465 | from socket import inet_ntoa as f, inet_ntop, AF_INET |
| 466 | g = lambda a: inet_ntop(AF_INET, a) |
| 467 | |
| 468 | self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00')) |
| 469 | self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55')) |
| 470 | self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff')) |
| 471 | self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04')) |
Tim Peters | c2659cf | 2003-05-12 20:19:37 +0000 | [diff] [blame] | 472 | |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 473 | self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00')) |
| 474 | self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55')) |
| 475 | self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff')) |
| 476 | |
| 477 | def testStringToIPv6(self): |
Guido van Rossum | f4001ee | 2003-04-25 15:11:23 +0000 | [diff] [blame] | 478 | if not hasattr(socket, 'inet_ntop'): |
| 479 | return # No inet_ntop() on this platform |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 480 | try: |
| 481 | from socket import inet_ntop, AF_INET6, has_ipv6 |
| 482 | if not has_ipv6: |
| 483 | return |
| 484 | except ImportError: |
| 485 | return |
| 486 | f = lambda a: inet_ntop(AF_INET6, a) |
| 487 | |
| 488 | self.assertEquals('::', f('\x00' * 16)) |
| 489 | self.assertEquals('::1', f('\x00' * 15 + '\x01')) |
| 490 | self.assertEquals( |
| 491 | 'aef:b01:506:1001:ffff:9997:55:170', |
| 492 | f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') |
| 493 | ) |
| 494 | |
Guido van Rossum | b6cc7d2 | 2002-07-19 12:46:46 +0000 | [diff] [blame] | 495 | # XXX The following don't test module-level functionality... |
Guido van Rossum | 9d0c8ce | 2002-07-18 17:08:35 +0000 | [diff] [blame] | 496 | |
Gregory P. Smith | de1a8b7 | 2009-01-31 22:57:30 +0000 | [diff] [blame] | 497 | def _get_unused_port(self, bind_address='0.0.0.0'): |
| 498 | """Use a temporary socket to elicit an unused ephemeral port. |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 499 | |
Gregory P. Smith | de1a8b7 | 2009-01-31 22:57:30 +0000 | [diff] [blame] | 500 | Args: |
| 501 | bind_address: Hostname or IP address to search for a port on. |
| 502 | |
| 503 | Returns: A most likely to be unused port. |
| 504 | """ |
| 505 | tempsock = socket.socket() |
| 506 | tempsock.bind((bind_address, 0)) |
| 507 | host, port = tempsock.getsockname() |
| 508 | tempsock.close() |
| 509 | return port |
| 510 | |
| 511 | def testSockName(self): |
| 512 | # Testing getsockname() |
| 513 | port = self._get_unused_port() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 514 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 515 | sock.bind(("0.0.0.0", port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 516 | name = sock.getsockname() |
Neal Norwitz | 4a9ff16 | 2006-06-11 21:38:38 +0000 | [diff] [blame] | 517 | # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate |
| 518 | # it reasonable to get the host's addr in addition to 0.0.0.0. |
| 519 | # At least for eCos. This is required for the S/390 to pass. |
| 520 | my_ip_addr = socket.gethostbyname(socket.gethostname()) |
Ezio Melotti | aa98058 | 2010-01-23 23:04:36 +0000 | [diff] [blame] | 521 | self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 522 | self.assertEqual(name[1], port) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 523 | |
| 524 | def testGetSockOpt(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 525 | # Testing getsockopt() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 526 | # We know a socket should start without reuse==0 |
| 527 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 528 | reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 529 | self.assertFalse(reuse != 0, "initial mode is reuse") |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 530 | |
| 531 | def testSetSockOpt(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 532 | # Testing setsockopt() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 533 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 534 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 535 | reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 536 | self.assertFalse(reuse == 0, "failed to set reuse mode") |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 537 | |
Guido van Rossum | b6cc7d2 | 2002-07-19 12:46:46 +0000 | [diff] [blame] | 538 | def testSendAfterClose(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 539 | # testing send() after close() with timeout |
Guido van Rossum | b6cc7d2 | 2002-07-19 12:46:46 +0000 | [diff] [blame] | 540 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 541 | sock.settimeout(1) |
| 542 | sock.close() |
| 543 | self.assertRaises(socket.error, sock.send, "spam") |
| 544 | |
Georg Brandl | bb03ac0 | 2006-03-21 18:17:25 +0000 | [diff] [blame] | 545 | def testNewAttributes(self): |
| 546 | # testing .family, .type and .protocol |
Georg Brandl | bc45a3f | 2006-03-17 19:17:34 +0000 | [diff] [blame] | 547 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Georg Brandl | bb03ac0 | 2006-03-21 18:17:25 +0000 | [diff] [blame] | 548 | self.assertEqual(sock.family, socket.AF_INET) |
| 549 | self.assertEqual(sock.type, socket.SOCK_STREAM) |
| 550 | self.assertEqual(sock.proto, 0) |
Georg Brandl | bc45a3f | 2006-03-17 19:17:34 +0000 | [diff] [blame] | 551 | sock.close() |
| 552 | |
Gregory P. Smith | de1a8b7 | 2009-01-31 22:57:30 +0000 | [diff] [blame] | 553 | def test_getsockaddrarg(self): |
| 554 | host = '0.0.0.0' |
| 555 | port = self._get_unused_port(bind_address=host) |
| 556 | big_port = port + 65536 |
| 557 | neg_port = port - 65536 |
| 558 | sock = socket.socket() |
| 559 | try: |
| 560 | self.assertRaises(OverflowError, sock.bind, (host, big_port)) |
| 561 | self.assertRaises(OverflowError, sock.bind, (host, neg_port)) |
| 562 | sock.bind((host, port)) |
| 563 | finally: |
| 564 | sock.close() |
| 565 | |
Christian Heimes | a47b75b | 2008-01-04 15:48:06 +0000 | [diff] [blame] | 566 | def test_sock_ioctl(self): |
| 567 | if os.name != "nt": |
| 568 | return |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 569 | self.assertTrue(hasattr(socket.socket, 'ioctl')) |
| 570 | self.assertTrue(hasattr(socket, 'SIO_RCVALL')) |
| 571 | self.assertTrue(hasattr(socket, 'RCVALL_ON')) |
| 572 | self.assertTrue(hasattr(socket, 'RCVALL_OFF')) |
Kristján Valur Jónsson | 2fcd03b | 2009-09-25 15:19:51 +0000 | [diff] [blame] | 573 | self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS')) |
| 574 | s = socket.socket() |
| 575 | self.assertRaises(ValueError, s.ioctl, -1, None) |
| 576 | s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100)) |
Christian Heimes | a47b75b | 2008-01-04 15:48:06 +0000 | [diff] [blame] | 577 | |
Giampaolo Rodolà | 633e474 | 2010-08-14 17:04:46 +0000 | [diff] [blame] | 578 | def testGetaddrinfo(self): |
| 579 | try: |
| 580 | socket.getaddrinfo('localhost', 80) |
| 581 | except socket.gaierror as err: |
| 582 | if err.errno == socket.EAI_SERVICE: |
| 583 | # see http://bugs.python.org/issue1282647 |
| 584 | self.skipTest("buggy libc version") |
| 585 | raise |
| 586 | # len of every sequence is supposed to be == 5 |
| 587 | for info in socket.getaddrinfo(HOST, None): |
| 588 | self.assertEqual(len(info), 5) |
| 589 | # host can be a domain name, a string representation of an |
| 590 | # IPv4/v6 address or None |
| 591 | socket.getaddrinfo('localhost', 80) |
| 592 | socket.getaddrinfo('127.0.0.1', 80) |
| 593 | socket.getaddrinfo(None, 80) |
| 594 | if SUPPORTS_IPV6: |
| 595 | socket.getaddrinfo('::1', 80) |
| 596 | # port can be a string service name such as "http", a numeric |
| 597 | # port number or None |
| 598 | socket.getaddrinfo(HOST, "http") |
| 599 | socket.getaddrinfo(HOST, 80) |
| 600 | socket.getaddrinfo(HOST, None) |
| 601 | # test family and socktype filters |
| 602 | infos = socket.getaddrinfo(HOST, None, socket.AF_INET) |
| 603 | for family, _, _, _, _ in infos: |
| 604 | self.assertEqual(family, socket.AF_INET) |
| 605 | infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) |
| 606 | for _, socktype, _, _, _ in infos: |
| 607 | self.assertEqual(socktype, socket.SOCK_STREAM) |
| 608 | # test proto and flags arguments |
Giampaolo Rodolà | 8a9b222 | 2010-08-16 05:10:30 +0000 | [diff] [blame] | 609 | socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) |
Giampaolo Rodolà | 633e474 | 2010-08-14 17:04:46 +0000 | [diff] [blame] | 610 | socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) |
| 611 | # a server willing to support both IPv4 and IPv6 will |
| 612 | # usually do this |
| 613 | socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, |
| 614 | socket.AI_PASSIVE) |
| 615 | |
Christian Heimes | a47b75b | 2008-01-04 15:48:06 +0000 | [diff] [blame] | 616 | |
Antoine Pitrou | 66b5df6 | 2010-09-27 18:16:46 +0000 | [diff] [blame] | 617 | def check_sendall_interrupted(self, with_timeout): |
| 618 | # socketpair() is not stricly required, but it makes things easier. |
| 619 | if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'): |
| 620 | self.skipTest("signal.alarm and socket.socketpair required for this test") |
| 621 | # Our signal handlers clobber the C errno by calling a math function |
| 622 | # with an invalid domain value. |
| 623 | def ok_handler(*args): |
| 624 | self.assertRaises(ValueError, math.acosh, 0) |
| 625 | def raising_handler(*args): |
| 626 | self.assertRaises(ValueError, math.acosh, 0) |
| 627 | 1 // 0 |
| 628 | c, s = socket.socketpair() |
| 629 | old_alarm = signal.signal(signal.SIGALRM, raising_handler) |
| 630 | try: |
| 631 | if with_timeout: |
| 632 | # Just above the one second minimum for signal.alarm |
| 633 | c.settimeout(1.5) |
| 634 | with self.assertRaises(ZeroDivisionError): |
| 635 | signal.alarm(1) |
| 636 | c.sendall(b"x" * (1024**2)) |
| 637 | if with_timeout: |
| 638 | signal.signal(signal.SIGALRM, ok_handler) |
| 639 | signal.alarm(1) |
| 640 | self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2)) |
| 641 | finally: |
| 642 | signal.signal(signal.SIGALRM, old_alarm) |
| 643 | c.close() |
| 644 | s.close() |
| 645 | |
| 646 | def test_sendall_interrupted(self): |
| 647 | self.check_sendall_interrupted(False) |
| 648 | |
| 649 | def test_sendall_interrupted_with_timeout(self): |
| 650 | self.check_sendall_interrupted(True) |
| 651 | |
| 652 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 653 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 654 | class BasicTCPTest(SocketConnectedTest): |
| 655 | |
| 656 | def __init__(self, methodName='runTest'): |
| 657 | SocketConnectedTest.__init__(self, methodName=methodName) |
| 658 | |
| 659 | def testRecv(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 660 | # Testing large receive over TCP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 661 | msg = self.cli_conn.recv(1024) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 662 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 663 | |
| 664 | def _testRecv(self): |
| 665 | self.serv_conn.send(MSG) |
| 666 | |
| 667 | def testOverFlowRecv(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 668 | # Testing receive in chunks over TCP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 669 | seg1 = self.cli_conn.recv(len(MSG) - 3) |
| 670 | seg2 = self.cli_conn.recv(1024) |
Guido van Rossum | ab65996 | 2002-06-12 21:29:43 +0000 | [diff] [blame] | 671 | msg = seg1 + seg2 |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 672 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 673 | |
| 674 | def _testOverFlowRecv(self): |
| 675 | self.serv_conn.send(MSG) |
| 676 | |
| 677 | def testRecvFrom(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 678 | # Testing large recvfrom() over TCP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 679 | msg, addr = self.cli_conn.recvfrom(1024) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 680 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 681 | |
| 682 | def _testRecvFrom(self): |
| 683 | self.serv_conn.send(MSG) |
| 684 | |
| 685 | def testOverFlowRecvFrom(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 686 | # Testing recvfrom() in chunks over TCP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 687 | seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) |
| 688 | seg2, addr = self.cli_conn.recvfrom(1024) |
Guido van Rossum | ab65996 | 2002-06-12 21:29:43 +0000 | [diff] [blame] | 689 | msg = seg1 + seg2 |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 690 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 691 | |
| 692 | def _testOverFlowRecvFrom(self): |
| 693 | self.serv_conn.send(MSG) |
| 694 | |
| 695 | def testSendAll(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 696 | # Testing sendall() with a 2048 byte string over TCP |
Guido van Rossum | e531e29 | 2002-08-08 20:28:34 +0000 | [diff] [blame] | 697 | msg = '' |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 698 | while 1: |
| 699 | read = self.cli_conn.recv(1024) |
| 700 | if not read: |
| 701 | break |
Guido van Rossum | e531e29 | 2002-08-08 20:28:34 +0000 | [diff] [blame] | 702 | msg += read |
| 703 | self.assertEqual(msg, 'f' * 2048) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 704 | |
| 705 | def _testSendAll(self): |
Guido van Rossum | ab65996 | 2002-06-12 21:29:43 +0000 | [diff] [blame] | 706 | big_chunk = 'f' * 2048 |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 707 | self.serv_conn.sendall(big_chunk) |
| 708 | |
| 709 | def testFromFd(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 710 | # Testing fromfd() |
Guido van Rossum | 8e95ca8 | 2002-06-12 20:55:17 +0000 | [diff] [blame] | 711 | if not hasattr(socket, "fromfd"): |
Guido van Rossum | 6fb3d5e | 2002-06-12 20:48:59 +0000 | [diff] [blame] | 712 | return # On Windows, this doesn't exist |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 713 | fd = self.cli_conn.fileno() |
| 714 | sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) |
| 715 | msg = sock.recv(1024) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 716 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 717 | |
| 718 | def _testFromFd(self): |
| 719 | self.serv_conn.send(MSG) |
| 720 | |
| 721 | def testShutdown(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 722 | # Testing shutdown() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 723 | msg = self.cli_conn.recv(1024) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 724 | self.assertEqual(msg, MSG) |
Mark Dickinson | e82cdae | 2009-01-15 14:54:37 +0000 | [diff] [blame] | 725 | # wait for _testShutdown to finish: on OS X, when the server |
| 726 | # closes the connection the client also becomes disconnected, |
Mark Dickinson | 0e15182 | 2009-01-15 14:58:28 +0000 | [diff] [blame] | 727 | # and the client's shutdown call will fail. (Issue #4397.) |
Mark Dickinson | e82cdae | 2009-01-15 14:54:37 +0000 | [diff] [blame] | 728 | self.done.wait() |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 729 | |
| 730 | def _testShutdown(self): |
| 731 | self.serv_conn.send(MSG) |
| 732 | self.serv_conn.shutdown(2) |
| 733 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 734 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 735 | class BasicUDPTest(ThreadedUDPSocketTest): |
| 736 | |
| 737 | def __init__(self, methodName='runTest'): |
| 738 | ThreadedUDPSocketTest.__init__(self, methodName=methodName) |
| 739 | |
| 740 | def testSendtoAndRecv(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 741 | # Testing sendto() and Recv() over UDP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 742 | msg = self.serv.recv(len(MSG)) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 743 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 744 | |
| 745 | def _testSendtoAndRecv(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 746 | self.cli.sendto(MSG, 0, (HOST, self.port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 747 | |
Guido van Rossum | 1c93801 | 2002-06-12 21:17:20 +0000 | [diff] [blame] | 748 | def testRecvFrom(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 749 | # Testing recvfrom() over UDP |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 750 | msg, addr = self.serv.recvfrom(len(MSG)) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 751 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 752 | |
Guido van Rossum | 1c93801 | 2002-06-12 21:17:20 +0000 | [diff] [blame] | 753 | def _testRecvFrom(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 754 | self.cli.sendto(MSG, 0, (HOST, self.port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 755 | |
Facundo Batista | 1fe9f96 | 2007-03-28 03:45:20 +0000 | [diff] [blame] | 756 | def testRecvFromNegative(self): |
| 757 | # Negative lengths passed to recvfrom should give ValueError. |
| 758 | self.assertRaises(ValueError, self.serv.recvfrom, -1) |
| 759 | |
| 760 | def _testRecvFromNegative(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 761 | self.cli.sendto(MSG, 0, (HOST, self.port)) |
Facundo Batista | 1fe9f96 | 2007-03-28 03:45:20 +0000 | [diff] [blame] | 762 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 763 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Martin v. Löwis | 7596e83 | 2006-07-01 15:33:37 +0000 | [diff] [blame] | 764 | class TCPCloserTest(ThreadedTCPSocketTest): |
| 765 | |
| 766 | def testClose(self): |
| 767 | conn, addr = self.serv.accept() |
| 768 | conn.close() |
| 769 | |
| 770 | sd = self.cli |
| 771 | read, write, err = select.select([sd], [], [], 1.0) |
| 772 | self.assertEqual(read, [sd]) |
| 773 | self.assertEqual(sd.recv(1), '') |
| 774 | |
| 775 | def _testClose(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 776 | self.cli.connect((HOST, self.port)) |
Martin v. Löwis | 7596e83 | 2006-07-01 15:33:37 +0000 | [diff] [blame] | 777 | time.sleep(1.0) |
| 778 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 779 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Dave Cole | 331708b | 2004-08-09 04:51:41 +0000 | [diff] [blame] | 780 | class BasicSocketPairTest(SocketPairTest): |
| 781 | |
| 782 | def __init__(self, methodName='runTest'): |
| 783 | SocketPairTest.__init__(self, methodName=methodName) |
| 784 | |
| 785 | def testRecv(self): |
| 786 | msg = self.serv.recv(1024) |
| 787 | self.assertEqual(msg, MSG) |
| 788 | |
| 789 | def _testRecv(self): |
| 790 | self.cli.send(MSG) |
| 791 | |
| 792 | def testSend(self): |
| 793 | self.serv.send(MSG) |
| 794 | |
| 795 | def _testSend(self): |
| 796 | msg = self.cli.recv(1024) |
| 797 | self.assertEqual(msg, MSG) |
| 798 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 799 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 800 | class NonBlockingTCPTests(ThreadedTCPSocketTest): |
| 801 | |
| 802 | def __init__(self, methodName='runTest'): |
| 803 | ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
| 804 | |
| 805 | def testSetBlocking(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 806 | # Testing whether set blocking works |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 807 | self.serv.setblocking(0) |
| 808 | start = time.time() |
| 809 | try: |
| 810 | self.serv.accept() |
| 811 | except socket.error: |
| 812 | pass |
| 813 | end = time.time() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 814 | self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.") |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 815 | |
| 816 | def _testSetBlocking(self): |
Barry Warsaw | 6870bba | 2001-03-23 17:40:16 +0000 | [diff] [blame] | 817 | pass |
Barry Warsaw | cf3d4b5 | 1997-01-03 20:03:32 +0000 | [diff] [blame] | 818 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 819 | def testAccept(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 820 | # Testing non-blocking accept |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 821 | self.serv.setblocking(0) |
Guido van Rossum | 41360a4 | 1998-03-26 19:42:58 +0000 | [diff] [blame] | 822 | try: |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 823 | conn, addr = self.serv.accept() |
| 824 | except socket.error: |
| 825 | pass |
| 826 | else: |
| 827 | self.fail("Error trying to do non-blocking accept.") |
| 828 | read, write, err = select.select([self.serv], [], []) |
| 829 | if self.serv in read: |
| 830 | conn, addr = self.serv.accept() |
| 831 | else: |
| 832 | self.fail("Error trying to do accept after select.") |
Guido van Rossum | 67f7a38 | 2002-06-06 21:08:16 +0000 | [diff] [blame] | 833 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 834 | def _testAccept(self): |
Guido van Rossum | b6cc7d2 | 2002-07-19 12:46:46 +0000 | [diff] [blame] | 835 | time.sleep(0.1) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 836 | self.cli.connect((HOST, self.port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 837 | |
| 838 | def testConnect(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 839 | # Testing non-blocking connect |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 840 | conn, addr = self.serv.accept() |
| 841 | |
| 842 | def _testConnect(self): |
Guido van Rossum | 7b8bac1 | 2002-06-13 16:07:04 +0000 | [diff] [blame] | 843 | self.cli.settimeout(10) |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 844 | self.cli.connect((HOST, self.port)) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 845 | |
| 846 | def testRecv(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 847 | # Testing non-blocking recv |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 848 | conn, addr = self.serv.accept() |
| 849 | conn.setblocking(0) |
| 850 | try: |
| 851 | msg = conn.recv(len(MSG)) |
| 852 | except socket.error: |
| 853 | pass |
| 854 | else: |
| 855 | self.fail("Error trying to do non-blocking recv.") |
| 856 | read, write, err = select.select([conn], [], []) |
| 857 | if conn in read: |
| 858 | msg = conn.recv(len(MSG)) |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 859 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 860 | else: |
| 861 | self.fail("Error during select call to non-blocking socket.") |
| 862 | |
| 863 | def _testRecv(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 864 | self.cli.connect((HOST, self.port)) |
Guido van Rossum | b6cc7d2 | 2002-07-19 12:46:46 +0000 | [diff] [blame] | 865 | time.sleep(0.1) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 866 | self.cli.send(MSG) |
| 867 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 868 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 869 | class FileObjectClassTestCase(SocketConnectedTest): |
| 870 | |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 871 | bufsize = -1 # Use default buffer size |
| 872 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 873 | def __init__(self, methodName='runTest'): |
| 874 | SocketConnectedTest.__init__(self, methodName=methodName) |
| 875 | |
| 876 | def setUp(self): |
| 877 | SocketConnectedTest.setUp(self) |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 878 | self.serv_file = self.cli_conn.makefile('rb', self.bufsize) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 879 | |
| 880 | def tearDown(self): |
| 881 | self.serv_file.close() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 882 | self.assertTrue(self.serv_file.closed) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 883 | self.serv_file = None |
| 884 | SocketConnectedTest.tearDown(self) |
| 885 | |
| 886 | def clientSetUp(self): |
| 887 | SocketConnectedTest.clientSetUp(self) |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 888 | self.cli_file = self.serv_conn.makefile('wb') |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 889 | |
| 890 | def clientTearDown(self): |
| 891 | self.cli_file.close() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 892 | self.assertTrue(self.cli_file.closed) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 893 | self.cli_file = None |
| 894 | SocketConnectedTest.clientTearDown(self) |
| 895 | |
| 896 | def testSmallRead(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 897 | # Performing small file read test |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 898 | first_seg = self.serv_file.read(len(MSG)-3) |
| 899 | second_seg = self.serv_file.read(3) |
Guido van Rossum | ab65996 | 2002-06-12 21:29:43 +0000 | [diff] [blame] | 900 | msg = first_seg + second_seg |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 901 | self.assertEqual(msg, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 902 | |
| 903 | def _testSmallRead(self): |
| 904 | self.cli_file.write(MSG) |
| 905 | self.cli_file.flush() |
| 906 | |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 907 | def testFullRead(self): |
| 908 | # read until EOF |
| 909 | msg = self.serv_file.read() |
| 910 | self.assertEqual(msg, MSG) |
| 911 | |
| 912 | def _testFullRead(self): |
| 913 | self.cli_file.write(MSG) |
| 914 | self.cli_file.close() |
| 915 | |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 916 | def testUnbufferedRead(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 917 | # Performing unbuffered file read test |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 918 | buf = '' |
| 919 | while 1: |
| 920 | char = self.serv_file.read(1) |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 921 | if not char: |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 922 | break |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 923 | buf += char |
| 924 | self.assertEqual(buf, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 925 | |
| 926 | def _testUnbufferedRead(self): |
| 927 | self.cli_file.write(MSG) |
| 928 | self.cli_file.flush() |
| 929 | |
| 930 | def testReadline(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 931 | # Performing file readline test |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 932 | line = self.serv_file.readline() |
Guido van Rossum | 7648968 | 2002-06-12 20:38:30 +0000 | [diff] [blame] | 933 | self.assertEqual(line, MSG) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 934 | |
| 935 | def _testReadline(self): |
| 936 | self.cli_file.write(MSG) |
| 937 | self.cli_file.flush() |
| 938 | |
Gregory P. Smith | 24237ea | 2008-05-05 21:53:45 +0000 | [diff] [blame] | 939 | def testReadlineAfterRead(self): |
| 940 | a_baloo_is = self.serv_file.read(len("A baloo is")) |
| 941 | self.assertEqual("A baloo is", a_baloo_is) |
| 942 | _a_bear = self.serv_file.read(len(" a bear")) |
| 943 | self.assertEqual(" a bear", _a_bear) |
| 944 | line = self.serv_file.readline() |
| 945 | self.assertEqual("\n", line) |
| 946 | line = self.serv_file.readline() |
| 947 | self.assertEqual("A BALOO IS A BEAR.\n", line) |
| 948 | line = self.serv_file.readline() |
| 949 | self.assertEqual(MSG, line) |
| 950 | |
| 951 | def _testReadlineAfterRead(self): |
| 952 | self.cli_file.write("A baloo is a bear\n") |
| 953 | self.cli_file.write("A BALOO IS A BEAR.\n") |
| 954 | self.cli_file.write(MSG) |
| 955 | self.cli_file.flush() |
| 956 | |
| 957 | def testReadlineAfterReadNoNewline(self): |
| 958 | end_of_ = self.serv_file.read(len("End Of ")) |
| 959 | self.assertEqual("End Of ", end_of_) |
| 960 | line = self.serv_file.readline() |
| 961 | self.assertEqual("Line", line) |
| 962 | |
| 963 | def _testReadlineAfterReadNoNewline(self): |
| 964 | self.cli_file.write("End Of Line") |
| 965 | |
Tim Peters | 116d83c | 2004-03-28 02:20:45 +0000 | [diff] [blame] | 966 | def testClosedAttr(self): |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 967 | self.assertTrue(not self.serv_file.closed) |
Tim Peters | 116d83c | 2004-03-28 02:20:45 +0000 | [diff] [blame] | 968 | |
| 969 | def _testClosedAttr(self): |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 970 | self.assertTrue(not self.cli_file.closed) |
Tim Peters | 116d83c | 2004-03-28 02:20:45 +0000 | [diff] [blame] | 971 | |
Gregory P. Smith | c4ad034 | 2009-08-13 18:54:50 +0000 | [diff] [blame] | 972 | |
| 973 | class FileObjectInterruptedTestCase(unittest.TestCase): |
| 974 | """Test that the file object correctly handles EINTR internally.""" |
| 975 | |
| 976 | class MockSocket(object): |
| 977 | def __init__(self, recv_funcs=()): |
| 978 | # A generator that returns callables that we'll call for each |
| 979 | # call to recv(). |
| 980 | self._recv_step = iter(recv_funcs) |
| 981 | |
| 982 | def recv(self, size): |
| 983 | return self._recv_step.next()() |
| 984 | |
| 985 | @staticmethod |
| 986 | def _raise_eintr(): |
| 987 | raise socket.error(errno.EINTR) |
| 988 | |
| 989 | def _test_readline(self, size=-1, **kwargs): |
| 990 | mock_sock = self.MockSocket(recv_funcs=[ |
| 991 | lambda : "This is the first line\nAnd the sec", |
| 992 | self._raise_eintr, |
| 993 | lambda : "ond line is here\n", |
| 994 | lambda : "", |
| 995 | ]) |
| 996 | fo = socket._fileobject(mock_sock, **kwargs) |
| 997 | self.assertEquals(fo.readline(size), "This is the first line\n") |
| 998 | self.assertEquals(fo.readline(size), "And the second line is here\n") |
| 999 | |
| 1000 | def _test_read(self, size=-1, **kwargs): |
| 1001 | mock_sock = self.MockSocket(recv_funcs=[ |
| 1002 | lambda : "This is the first line\nAnd the sec", |
| 1003 | self._raise_eintr, |
| 1004 | lambda : "ond line is here\n", |
| 1005 | lambda : "", |
| 1006 | ]) |
| 1007 | fo = socket._fileobject(mock_sock, **kwargs) |
| 1008 | self.assertEquals(fo.read(size), "This is the first line\n" |
| 1009 | "And the second line is here\n") |
| 1010 | |
| 1011 | def test_default(self): |
| 1012 | self._test_readline() |
| 1013 | self._test_readline(size=100) |
| 1014 | self._test_read() |
| 1015 | self._test_read(size=100) |
| 1016 | |
| 1017 | def test_with_1k_buffer(self): |
| 1018 | self._test_readline(bufsize=1024) |
| 1019 | self._test_readline(size=100, bufsize=1024) |
| 1020 | self._test_read(bufsize=1024) |
| 1021 | self._test_read(size=100, bufsize=1024) |
| 1022 | |
| 1023 | def _test_readline_no_buffer(self, size=-1): |
| 1024 | mock_sock = self.MockSocket(recv_funcs=[ |
| 1025 | lambda : "aa", |
| 1026 | lambda : "\n", |
| 1027 | lambda : "BB", |
| 1028 | self._raise_eintr, |
| 1029 | lambda : "bb", |
| 1030 | lambda : "", |
| 1031 | ]) |
| 1032 | fo = socket._fileobject(mock_sock, bufsize=0) |
| 1033 | self.assertEquals(fo.readline(size), "aa\n") |
| 1034 | self.assertEquals(fo.readline(size), "BBbb") |
| 1035 | |
| 1036 | def test_no_buffer(self): |
| 1037 | self._test_readline_no_buffer() |
| 1038 | self._test_readline_no_buffer(size=4) |
| 1039 | self._test_read(bufsize=0) |
| 1040 | self._test_read(size=100, bufsize=0) |
| 1041 | |
| 1042 | |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1043 | class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 1044 | |
| 1045 | """Repeat the tests from FileObjectClassTestCase with bufsize==0. |
Tim Peters | 469cdad | 2002-08-08 20:19:19 +0000 | [diff] [blame] | 1046 | |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1047 | In this case (and in this case only), it should be possible to |
| 1048 | create a file object, read a line from it, create another file |
| 1049 | object, read another line from it, without loss of data in the |
| 1050 | first file object's buffer. Note that httplib relies on this |
| 1051 | when reading multiple requests from the same socket.""" |
| 1052 | |
| 1053 | bufsize = 0 # Use unbuffered mode |
| 1054 | |
| 1055 | def testUnbufferedReadline(self): |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 1056 | # Read a line, create a new file object, read another line with it |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1057 | line = self.serv_file.readline() # first line |
Guido van Rossum | 10e3f41 | 2002-08-07 19:02:49 +0000 | [diff] [blame] | 1058 | self.assertEqual(line, "A. " + MSG) # first line |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1059 | self.serv_file = self.cli_conn.makefile('rb', 0) |
| 1060 | line = self.serv_file.readline() # second line |
Guido van Rossum | 10e3f41 | 2002-08-07 19:02:49 +0000 | [diff] [blame] | 1061 | self.assertEqual(line, "B. " + MSG) # second line |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1062 | |
| 1063 | def _testUnbufferedReadline(self): |
Guido van Rossum | 10e3f41 | 2002-08-07 19:02:49 +0000 | [diff] [blame] | 1064 | self.cli_file.write("A. " + MSG) |
| 1065 | self.cli_file.write("B. " + MSG) |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1066 | self.cli_file.flush() |
| 1067 | |
Guido van Rossum | 8c94383 | 2002-08-08 01:00:28 +0000 | [diff] [blame] | 1068 | class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 1069 | |
| 1070 | bufsize = 1 # Default-buffered for reading; line-buffered for writing |
| 1071 | |
| 1072 | |
| 1073 | class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 1074 | |
| 1075 | bufsize = 2 # Exercise the buffering code |
Guido van Rossum | e9f6614 | 2002-08-07 15:46:19 +0000 | [diff] [blame] | 1076 | |
Georg Brandl | dd7b052 | 2007-01-21 10:35:10 +0000 | [diff] [blame] | 1077 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1078 | class NetworkConnectionTest(object): |
| 1079 | """Prove network connection.""" |
| 1080 | def clientSetUp(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1081 | # We're inherited below by BasicTCPTest2, which also inherits |
| 1082 | # BasicTCPTest, which defines self.port referenced below. |
| 1083 | self.cli = socket.create_connection((HOST, self.port)) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1084 | self.serv_conn = self.cli |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 1085 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1086 | class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): |
| 1087 | """Tests that NetworkConnection does not break existing TCP functionality. |
| 1088 | """ |
| 1089 | |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1090 | class NetworkConnectionNoServer(unittest.TestCase): |
Antoine Pitrou | c818ed4 | 2010-09-07 21:40:25 +0000 | [diff] [blame] | 1091 | class MockSocket(socket.socket): |
| 1092 | def connect(self, *args): |
| 1093 | raise socket.timeout('timed out') |
| 1094 | |
| 1095 | @contextlib.contextmanager |
| 1096 | def mocked_socket_module(self): |
| 1097 | """Return a socket which times out on connect""" |
| 1098 | old_socket = socket.socket |
| 1099 | socket.socket = self.MockSocket |
| 1100 | try: |
| 1101 | yield |
| 1102 | finally: |
| 1103 | socket.socket = old_socket |
| 1104 | |
| 1105 | def test_connect(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1106 | port = test_support.find_unused_port() |
Antoine Pitrou | c818ed4 | 2010-09-07 21:40:25 +0000 | [diff] [blame] | 1107 | cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1108 | with self.assertRaises(socket.error) as cm: |
| 1109 | cli.connect((HOST, port)) |
| 1110 | self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) |
| 1111 | |
| 1112 | def test_create_connection(self): |
| 1113 | # Issue #9792: errors raised by create_connection() should have |
| 1114 | # a proper errno attribute. |
| 1115 | port = test_support.find_unused_port() |
| 1116 | with self.assertRaises(socket.error) as cm: |
| 1117 | socket.create_connection((HOST, port)) |
| 1118 | self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) |
| 1119 | |
| 1120 | def test_create_connection_timeout(self): |
| 1121 | # Issue #9792: create_connection() should not recast timeout errors |
| 1122 | # as generic socket errors. |
| 1123 | with self.mocked_socket_module(): |
| 1124 | with self.assertRaises(socket.timeout): |
| 1125 | socket.create_connection((HOST, 1234)) |
| 1126 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1127 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 1128 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1129 | class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): |
| 1130 | |
| 1131 | def __init__(self, methodName='runTest'): |
| 1132 | SocketTCPTest.__init__(self, methodName=methodName) |
| 1133 | ThreadableTest.__init__(self) |
| 1134 | |
| 1135 | def clientSetUp(self): |
Gregory P. Smith | 79a3eb1 | 2010-01-03 01:29:44 +0000 | [diff] [blame] | 1136 | self.source_port = test_support.find_unused_port() |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1137 | |
| 1138 | def clientTearDown(self): |
| 1139 | self.cli.close() |
| 1140 | self.cli = None |
| 1141 | ThreadableTest.clientTearDown(self) |
| 1142 | |
| 1143 | def _justAccept(self): |
| 1144 | conn, addr = self.serv.accept() |
| 1145 | |
| 1146 | testFamily = _justAccept |
| 1147 | def _testFamily(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1148 | self.cli = socket.create_connection((HOST, self.port), timeout=30) |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1149 | self.assertEqual(self.cli.family, 2) |
| 1150 | |
Gregory P. Smith | 49d709c | 2010-01-03 15:05:52 +0000 | [diff] [blame] | 1151 | testSourceAddress = _justAccept |
| 1152 | def _testSourceAddress(self): |
Gregory P. Smith | 79a3eb1 | 2010-01-03 01:29:44 +0000 | [diff] [blame] | 1153 | self.cli = socket.create_connection((HOST, self.port), timeout=30, |
| 1154 | source_address=('', self.source_port)) |
| 1155 | self.assertEqual(self.cli.getsockname()[1], self.source_port) |
Gregory P. Smith | 49d709c | 2010-01-03 15:05:52 +0000 | [diff] [blame] | 1156 | # The port number being used is sufficient to show that the bind() |
| 1157 | # call happened. |
Gregory P. Smith | 79a3eb1 | 2010-01-03 01:29:44 +0000 | [diff] [blame] | 1158 | |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 1159 | testTimeoutDefault = _justAccept |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1160 | def _testTimeoutDefault(self): |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 1161 | # passing no explicit timeout uses socket's global default |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1162 | self.assertTrue(socket.getdefaulttimeout() is None) |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 1163 | socket.setdefaulttimeout(42) |
| 1164 | try: |
| 1165 | self.cli = socket.create_connection((HOST, self.port)) |
| 1166 | finally: |
| 1167 | socket.setdefaulttimeout(None) |
| 1168 | self.assertEquals(self.cli.gettimeout(), 42) |
| 1169 | |
| 1170 | testTimeoutNone = _justAccept |
| 1171 | def _testTimeoutNone(self): |
| 1172 | # None timeout means the same as sock.settimeout(None) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1173 | self.assertTrue(socket.getdefaulttimeout() is None) |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 1174 | socket.setdefaulttimeout(30) |
| 1175 | try: |
| 1176 | self.cli = socket.create_connection((HOST, self.port), timeout=None) |
| 1177 | finally: |
| 1178 | socket.setdefaulttimeout(None) |
| 1179 | self.assertEqual(self.cli.gettimeout(), None) |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 1180 | |
| 1181 | testTimeoutValueNamed = _justAccept |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1182 | def _testTimeoutValueNamed(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1183 | self.cli = socket.create_connection((HOST, self.port), timeout=30) |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1184 | self.assertEqual(self.cli.gettimeout(), 30) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1185 | |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 1186 | testTimeoutValueNonamed = _justAccept |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1187 | def _testTimeoutValueNonamed(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1188 | self.cli = socket.create_connection((HOST, self.port), 30) |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1189 | self.assertEqual(self.cli.gettimeout(), 30) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1190 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 1191 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1192 | class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest): |
| 1193 | |
| 1194 | def __init__(self, methodName='runTest'): |
| 1195 | SocketTCPTest.__init__(self, methodName=methodName) |
| 1196 | ThreadableTest.__init__(self) |
| 1197 | |
| 1198 | def clientSetUp(self): |
| 1199 | pass |
| 1200 | |
| 1201 | def clientTearDown(self): |
| 1202 | self.cli.close() |
| 1203 | self.cli = None |
| 1204 | ThreadableTest.clientTearDown(self) |
| 1205 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1206 | def testInsideTimeout(self): |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1207 | conn, addr = self.serv.accept() |
| 1208 | time.sleep(3) |
| 1209 | conn.send("done!") |
| 1210 | testOutsideTimeout = testInsideTimeout |
| 1211 | |
| 1212 | def _testInsideTimeout(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1213 | self.cli = sock = socket.create_connection((HOST, self.port)) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1214 | data = sock.recv(5) |
| 1215 | self.assertEqual(data, "done!") |
| 1216 | |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1217 | def _testOutsideTimeout(self): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 1218 | self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1219 | self.assertRaises(socket.timeout, lambda: sock.recv(5)) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1220 | |
| 1221 | |
Georg Brandl | dd7b052 | 2007-01-21 10:35:10 +0000 | [diff] [blame] | 1222 | class Urllib2FileobjectTest(unittest.TestCase): |
| 1223 | |
| 1224 | # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that |
| 1225 | # it close the socket if the close c'tor argument is true |
| 1226 | |
| 1227 | def testClose(self): |
| 1228 | class MockSocket: |
| 1229 | closed = False |
| 1230 | def flush(self): pass |
| 1231 | def close(self): self.closed = True |
| 1232 | |
| 1233 | # must not close unless we request it: the original use of _fileobject |
| 1234 | # by module socket requires that the underlying socket not be closed until |
| 1235 | # the _socketobject that created the _fileobject is closed |
| 1236 | s = MockSocket() |
| 1237 | f = socket._fileobject(s) |
| 1238 | f.close() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1239 | self.assertTrue(not s.closed) |
Georg Brandl | dd7b052 | 2007-01-21 10:35:10 +0000 | [diff] [blame] | 1240 | |
| 1241 | s = MockSocket() |
| 1242 | f = socket._fileobject(s, close=True) |
| 1243 | f.close() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1244 | self.assertTrue(s.closed) |
Georg Brandl | dd7b052 | 2007-01-21 10:35:10 +0000 | [diff] [blame] | 1245 | |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1246 | class TCPTimeoutTest(SocketTCPTest): |
| 1247 | |
| 1248 | def testTCPTimeout(self): |
| 1249 | def raise_timeout(*args, **kwargs): |
| 1250 | self.serv.settimeout(1.0) |
| 1251 | self.serv.accept() |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1252 | self.assertRaises(socket.timeout, raise_timeout, |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1253 | "Error generating a timeout exception (TCP)") |
| 1254 | |
| 1255 | def testTimeoutZero(self): |
| 1256 | ok = False |
| 1257 | try: |
| 1258 | self.serv.settimeout(0.0) |
| 1259 | foo = self.serv.accept() |
| 1260 | except socket.timeout: |
| 1261 | self.fail("caught timeout instead of error (TCP)") |
| 1262 | except socket.error: |
| 1263 | ok = True |
| 1264 | except: |
| 1265 | self.fail("caught unexpected exception (TCP)") |
| 1266 | if not ok: |
| 1267 | self.fail("accept() returned success when we did not expect it") |
| 1268 | |
Neal Norwitz | 9b0ca79 | 2006-08-02 06:46:21 +0000 | [diff] [blame] | 1269 | def testInterruptedTimeout(self): |
| 1270 | # XXX I don't know how to do this test on MSWindows or any other |
| 1271 | # plaform that doesn't support signal.alarm() or os.kill(), though |
| 1272 | # the bug should have existed on all platforms. |
| 1273 | if not hasattr(signal, "alarm"): |
| 1274 | return # can only test on *nix |
| 1275 | self.serv.settimeout(5.0) # must be longer than alarm |
| 1276 | class Alarm(Exception): |
| 1277 | pass |
| 1278 | def alarm_handler(signal, frame): |
| 1279 | raise Alarm |
| 1280 | old_alarm = signal.signal(signal.SIGALRM, alarm_handler) |
| 1281 | try: |
| 1282 | signal.alarm(2) # POSIX allows alarm to be up to 1 second early |
| 1283 | try: |
| 1284 | foo = self.serv.accept() |
| 1285 | except socket.timeout: |
| 1286 | self.fail("caught timeout instead of Alarm") |
| 1287 | except Alarm: |
| 1288 | pass |
| 1289 | except: |
Jeffrey Yasskin | 36550bd | 2008-03-28 04:53:10 +0000 | [diff] [blame] | 1290 | self.fail("caught other exception instead of Alarm:" |
| 1291 | " %s(%s):\n%s" % |
| 1292 | (sys.exc_info()[:2] + (traceback.format_exc(),))) |
Neal Norwitz | 9b0ca79 | 2006-08-02 06:46:21 +0000 | [diff] [blame] | 1293 | else: |
| 1294 | self.fail("nothing caught") |
Jeffrey Yasskin | 36550bd | 2008-03-28 04:53:10 +0000 | [diff] [blame] | 1295 | finally: |
| 1296 | signal.alarm(0) # shut off alarm |
Neal Norwitz | 9b0ca79 | 2006-08-02 06:46:21 +0000 | [diff] [blame] | 1297 | except Alarm: |
| 1298 | self.fail("got Alarm in wrong place") |
| 1299 | finally: |
| 1300 | # no alarm can be pending. Safe to restore old handler. |
| 1301 | signal.signal(signal.SIGALRM, old_alarm) |
| 1302 | |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1303 | class UDPTimeoutTest(SocketTCPTest): |
| 1304 | |
| 1305 | def testUDPTimeout(self): |
| 1306 | def raise_timeout(*args, **kwargs): |
| 1307 | self.serv.settimeout(1.0) |
| 1308 | self.serv.recv(1024) |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1309 | self.assertRaises(socket.timeout, raise_timeout, |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1310 | "Error generating a timeout exception (UDP)") |
| 1311 | |
| 1312 | def testTimeoutZero(self): |
| 1313 | ok = False |
| 1314 | try: |
| 1315 | self.serv.settimeout(0.0) |
| 1316 | foo = self.serv.recv(1024) |
| 1317 | except socket.timeout: |
| 1318 | self.fail("caught timeout instead of error (UDP)") |
| 1319 | except socket.error: |
| 1320 | ok = True |
| 1321 | except: |
| 1322 | self.fail("caught unexpected exception (UDP)") |
| 1323 | if not ok: |
| 1324 | self.fail("recv() returned success when we did not expect it") |
| 1325 | |
| 1326 | class TestExceptions(unittest.TestCase): |
| 1327 | |
| 1328 | def testExceptionTree(self): |
Benjamin Peterson | 5c8da86 | 2009-06-30 22:57:08 +0000 | [diff] [blame] | 1329 | self.assertTrue(issubclass(socket.error, Exception)) |
| 1330 | self.assertTrue(issubclass(socket.herror, socket.error)) |
| 1331 | self.assertTrue(issubclass(socket.gaierror, socket.error)) |
| 1332 | self.assertTrue(issubclass(socket.timeout, socket.error)) |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1333 | |
Armin Rigo | a9017c3 | 2006-04-19 11:50:27 +0000 | [diff] [blame] | 1334 | class TestLinuxAbstractNamespace(unittest.TestCase): |
| 1335 | |
| 1336 | UNIX_PATH_MAX = 108 |
| 1337 | |
| 1338 | def testLinuxAbstractNamespace(self): |
| 1339 | address = "\x00python-test-hello\x00\xff" |
| 1340 | s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1341 | s1.bind(address) |
| 1342 | s1.listen(1) |
| 1343 | s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1344 | s2.connect(s1.getsockname()) |
| 1345 | s1.accept() |
| 1346 | self.assertEqual(s1.getsockname(), address) |
| 1347 | self.assertEqual(s2.getpeername(), address) |
| 1348 | |
| 1349 | def testMaxName(self): |
| 1350 | address = "\x00" + "h" * (self.UNIX_PATH_MAX - 1) |
| 1351 | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1352 | s.bind(address) |
| 1353 | self.assertEqual(s.getsockname(), address) |
| 1354 | |
| 1355 | def testNameOverflow(self): |
| 1356 | address = "\x00" + "h" * self.UNIX_PATH_MAX |
| 1357 | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1358 | self.assertRaises(socket.error, s.bind, address) |
| 1359 | |
Raymond Hettinger | 11a35f5 | 2003-06-29 04:40:22 +0000 | [diff] [blame] | 1360 | |
Victor Stinner | 6a10281 | 2010-04-27 23:55:59 +0000 | [diff] [blame] | 1361 | @unittest.skipUnless(thread, 'Threading required for this test.') |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1362 | class BufferIOTest(SocketConnectedTest): |
| 1363 | """ |
| 1364 | Test the buffer versions of socket.recv() and socket.send(). |
| 1365 | """ |
| 1366 | def __init__(self, methodName='runTest'): |
| 1367 | SocketConnectedTest.__init__(self, methodName=methodName) |
| 1368 | |
Antoine Pitrou | d7b731d | 2010-03-17 22:45:39 +0000 | [diff] [blame] | 1369 | def testRecvIntoArray(self): |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1370 | buf = array.array('c', ' '*1024) |
Martin Blais | af2ae72 | 2006-06-04 13:49:49 +0000 | [diff] [blame] | 1371 | nbytes = self.cli_conn.recv_into(buf) |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1372 | self.assertEqual(nbytes, len(MSG)) |
| 1373 | msg = buf.tostring()[:len(MSG)] |
| 1374 | self.assertEqual(msg, MSG) |
| 1375 | |
Antoine Pitrou | d7b731d | 2010-03-17 22:45:39 +0000 | [diff] [blame] | 1376 | def _testRecvIntoArray(self): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1377 | with test_support.check_py3k_warnings(): |
| 1378 | buf = buffer(MSG) |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1379 | self.serv_conn.send(buf) |
| 1380 | |
Antoine Pitrou | d7b731d | 2010-03-17 22:45:39 +0000 | [diff] [blame] | 1381 | def testRecvIntoBytearray(self): |
| 1382 | buf = bytearray(1024) |
| 1383 | nbytes = self.cli_conn.recv_into(buf) |
| 1384 | self.assertEqual(nbytes, len(MSG)) |
| 1385 | msg = buf[:len(MSG)] |
| 1386 | self.assertEqual(msg, MSG) |
| 1387 | |
| 1388 | _testRecvIntoBytearray = _testRecvIntoArray |
| 1389 | |
| 1390 | def testRecvIntoMemoryview(self): |
| 1391 | buf = bytearray(1024) |
| 1392 | nbytes = self.cli_conn.recv_into(memoryview(buf)) |
| 1393 | self.assertEqual(nbytes, len(MSG)) |
| 1394 | msg = buf[:len(MSG)] |
| 1395 | self.assertEqual(msg, MSG) |
| 1396 | |
| 1397 | _testRecvIntoMemoryview = _testRecvIntoArray |
| 1398 | |
| 1399 | def testRecvFromIntoArray(self): |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1400 | buf = array.array('c', ' '*1024) |
Martin Blais | af2ae72 | 2006-06-04 13:49:49 +0000 | [diff] [blame] | 1401 | nbytes, addr = self.cli_conn.recvfrom_into(buf) |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1402 | self.assertEqual(nbytes, len(MSG)) |
| 1403 | msg = buf.tostring()[:len(MSG)] |
| 1404 | self.assertEqual(msg, MSG) |
| 1405 | |
Antoine Pitrou | d7b731d | 2010-03-17 22:45:39 +0000 | [diff] [blame] | 1406 | def _testRecvFromIntoArray(self): |
Florent Xicluna | 0762788 | 2010-03-21 01:14:24 +0000 | [diff] [blame] | 1407 | with test_support.check_py3k_warnings(): |
| 1408 | buf = buffer(MSG) |
Martin Blais | 2856e5f | 2006-05-26 12:03:27 +0000 | [diff] [blame] | 1409 | self.serv_conn.send(buf) |
| 1410 | |
Antoine Pitrou | d7b731d | 2010-03-17 22:45:39 +0000 | [diff] [blame] | 1411 | def testRecvFromIntoBytearray(self): |
| 1412 | buf = bytearray(1024) |
| 1413 | nbytes, addr = self.cli_conn.recvfrom_into(buf) |
| 1414 | self.assertEqual(nbytes, len(MSG)) |
| 1415 | msg = buf[:len(MSG)] |
| 1416 | self.assertEqual(msg, MSG) |
| 1417 | |
| 1418 | _testRecvFromIntoBytearray = _testRecvFromIntoArray |
| 1419 | |
| 1420 | def testRecvFromIntoMemoryview(self): |
| 1421 | buf = bytearray(1024) |
| 1422 | nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf)) |
| 1423 | self.assertEqual(nbytes, len(MSG)) |
| 1424 | msg = buf[:len(MSG)] |
| 1425 | self.assertEqual(msg, MSG) |
| 1426 | |
| 1427 | _testRecvFromIntoMemoryview = _testRecvFromIntoArray |
| 1428 | |
Christian Heimes | fb2d25a | 2008-01-07 16:12:44 +0000 | [diff] [blame] | 1429 | |
| 1430 | TIPC_STYPE = 2000 |
| 1431 | TIPC_LOWER = 200 |
| 1432 | TIPC_UPPER = 210 |
| 1433 | |
| 1434 | def isTipcAvailable(): |
| 1435 | """Check if the TIPC module is loaded |
| 1436 | |
| 1437 | The TIPC module is not loaded automatically on Ubuntu and probably |
| 1438 | other Linux distros. |
| 1439 | """ |
| 1440 | if not hasattr(socket, "AF_TIPC"): |
| 1441 | return False |
| 1442 | if not os.path.isfile("/proc/modules"): |
| 1443 | return False |
| 1444 | with open("/proc/modules") as f: |
| 1445 | for line in f: |
| 1446 | if line.startswith("tipc "): |
| 1447 | return True |
Christian Heimes | f66f95d | 2008-01-08 03:40:04 +0000 | [diff] [blame] | 1448 | if test_support.verbose: |
Christian Heimes | fb2d25a | 2008-01-07 16:12:44 +0000 | [diff] [blame] | 1449 | print "TIPC module is not loaded, please 'sudo modprobe tipc'" |
| 1450 | return False |
| 1451 | |
| 1452 | class TIPCTest (unittest.TestCase): |
| 1453 | def testRDM(self): |
| 1454 | srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
| 1455 | cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
| 1456 | |
| 1457 | srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1458 | srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
| 1459 | TIPC_LOWER, TIPC_UPPER) |
| 1460 | srv.bind(srvaddr) |
| 1461 | |
| 1462 | sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
| 1463 | TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0) |
| 1464 | cli.sendto(MSG, sendaddr) |
| 1465 | |
| 1466 | msg, recvaddr = srv.recvfrom(1024) |
| 1467 | |
| 1468 | self.assertEqual(cli.getsockname(), recvaddr) |
| 1469 | self.assertEqual(msg, MSG) |
| 1470 | |
| 1471 | |
| 1472 | class TIPCThreadableTest (unittest.TestCase, ThreadableTest): |
| 1473 | def __init__(self, methodName = 'runTest'): |
| 1474 | unittest.TestCase.__init__(self, methodName = methodName) |
| 1475 | ThreadableTest.__init__(self) |
| 1476 | |
| 1477 | def setUp(self): |
| 1478 | self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
| 1479 | self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1480 | srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
| 1481 | TIPC_LOWER, TIPC_UPPER) |
| 1482 | self.srv.bind(srvaddr) |
| 1483 | self.srv.listen(5) |
| 1484 | self.serverExplicitReady() |
| 1485 | self.conn, self.connaddr = self.srv.accept() |
| 1486 | |
| 1487 | def clientSetUp(self): |
| 1488 | # The is a hittable race between serverExplicitReady() and the |
| 1489 | # accept() call; sleep a little while to avoid it, otherwise |
| 1490 | # we could get an exception |
| 1491 | time.sleep(0.1) |
| 1492 | self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
| 1493 | addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
| 1494 | TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0) |
| 1495 | self.cli.connect(addr) |
| 1496 | self.cliaddr = self.cli.getsockname() |
| 1497 | |
| 1498 | def testStream(self): |
| 1499 | msg = self.conn.recv(1024) |
| 1500 | self.assertEqual(msg, MSG) |
| 1501 | self.assertEqual(self.cliaddr, self.connaddr) |
| 1502 | |
| 1503 | def _testStream(self): |
| 1504 | self.cli.send(MSG) |
| 1505 | self.cli.close() |
| 1506 | |
| 1507 | |
Guido van Rossum | b995eb7 | 2002-07-31 16:08:40 +0000 | [diff] [blame] | 1508 | def test_main(): |
Martin v. Löwis | 7596e83 | 2006-07-01 15:33:37 +0000 | [diff] [blame] | 1509 | tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest, |
Ronald Oussoren | 9545a23 | 2010-05-05 19:09:31 +0000 | [diff] [blame] | 1510 | TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, |
| 1511 | UDPTimeoutTest ] |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1512 | |
| 1513 | tests.extend([ |
| 1514 | NonBlockingTCPTests, |
| 1515 | FileObjectClassTestCase, |
Gregory P. Smith | c4ad034 | 2009-08-13 18:54:50 +0000 | [diff] [blame] | 1516 | FileObjectInterruptedTestCase, |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1517 | UnbufferedFileObjectClassTestCase, |
| 1518 | LineBufferedFileObjectClassTestCase, |
Georg Brandl | dd7b052 | 2007-01-21 10:35:10 +0000 | [diff] [blame] | 1519 | SmallBufferedFileObjectClassTestCase, |
| 1520 | Urllib2FileobjectTest, |
Facundo Batista | b8af7bc | 2007-03-25 01:53:21 +0000 | [diff] [blame] | 1521 | NetworkConnectionNoServer, |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 1522 | NetworkConnectionAttributesTest, |
| 1523 | NetworkConnectionBehaviourTest, |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1524 | ]) |
Dave Cole | 331708b | 2004-08-09 04:51:41 +0000 | [diff] [blame] | 1525 | if hasattr(socket, "socketpair"): |
| 1526 | tests.append(BasicSocketPairTest) |
Armin Rigo | a9017c3 | 2006-04-19 11:50:27 +0000 | [diff] [blame] | 1527 | if sys.platform == 'linux2': |
| 1528 | tests.append(TestLinuxAbstractNamespace) |
Christian Heimes | fb2d25a | 2008-01-07 16:12:44 +0000 | [diff] [blame] | 1529 | if isTipcAvailable(): |
| 1530 | tests.append(TIPCTest) |
Christian Heimes | 4d7e670 | 2008-01-07 19:58:41 +0000 | [diff] [blame] | 1531 | tests.append(TIPCThreadableTest) |
Neal Norwitz | 9602cc2 | 2006-06-18 19:35:01 +0000 | [diff] [blame] | 1532 | |
| 1533 | thread_info = test_support.threading_setup() |
Walter Dörwald | 21d3a32 | 2003-05-01 17:45:56 +0000 | [diff] [blame] | 1534 | test_support.run_unittest(*tests) |
Neal Norwitz | 9602cc2 | 2006-06-18 19:35:01 +0000 | [diff] [blame] | 1535 | test_support.threading_cleanup(*thread_info) |
Guido van Rossum | 24e4af8 | 2002-06-12 19:18:08 +0000 | [diff] [blame] | 1536 | |
| 1537 | if __name__ == "__main__": |
Guido van Rossum | b995eb7 | 2002-07-31 16:08:40 +0000 | [diff] [blame] | 1538 | test_main() |