Senthil Kumaran | aa5f49e | 2010-10-03 18:26:07 +0000 | [diff] [blame] | 1 | import httplib |
R David Murray | b4b000f | 2015-03-22 15:15:44 -0400 | [diff] [blame] | 2 | import itertools |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 3 | import array |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 4 | import StringIO |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 5 | import socket |
Victor Stinner | 2c6aee9 | 2010-07-24 02:46:16 +0000 | [diff] [blame] | 6 | import errno |
Benjamin Peterson | e3e7d40 | 2014-11-23 21:02:02 -0600 | [diff] [blame] | 7 | import os |
Serhiy Storchaka | 80573bb | 2015-05-16 18:58:41 +0300 | [diff] [blame] | 8 | import tempfile |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 9 | |
Gregory P. Smith | 9d32521 | 2010-01-03 02:06:07 +0000 | [diff] [blame] | 10 | import unittest |
| 11 | TestCase = unittest.TestCase |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 12 | |
| 13 | from test import test_support |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 14 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 15 | here = os.path.dirname(__file__) |
| 16 | # Self-signed cert file for 'localhost' |
| 17 | CERT_localhost = os.path.join(here, 'keycert.pem') |
| 18 | # Self-signed cert file for 'fakehostname' |
| 19 | CERT_fakehostname = os.path.join(here, 'keycert2.pem') |
| 20 | # Self-signed cert file for self-signed.pythontest.net |
| 21 | CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem') |
| 22 | |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 23 | HOST = test_support.HOST |
| 24 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 25 | class FakeSocket: |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 26 | def __init__(self, text, fileclass=StringIO.StringIO, host=None, port=None): |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 27 | self.text = text |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 28 | self.fileclass = fileclass |
Martin v. Löwis | 040a927 | 2006-11-12 10:32:47 +0000 | [diff] [blame] | 29 | self.data = '' |
Serhiy Storchaka | d862db0 | 2014-12-01 13:07:28 +0200 | [diff] [blame] | 30 | self.file_closed = False |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 31 | self.host = host |
| 32 | self.port = port |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 33 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 34 | def sendall(self, data): |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 35 | self.data += ''.join(data) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 36 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 37 | def makefile(self, mode, bufsize=None): |
| 38 | if mode != 'r' and mode != 'rb': |
Neal Norwitz | 28bb572 | 2002-04-01 19:00:50 +0000 | [diff] [blame] | 39 | raise httplib.UnimplementedFileMode() |
Serhiy Storchaka | d862db0 | 2014-12-01 13:07:28 +0200 | [diff] [blame] | 40 | # keep the file around so we can check how much was read from it |
| 41 | self.file = self.fileclass(self.text) |
| 42 | self.file.close = self.file_close #nerf close () |
| 43 | return self.file |
| 44 | |
| 45 | def file_close(self): |
| 46 | self.file_closed = True |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 47 | |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 48 | def close(self): |
| 49 | pass |
| 50 | |
Victor Stinner | 2c6aee9 | 2010-07-24 02:46:16 +0000 | [diff] [blame] | 51 | class EPipeSocket(FakeSocket): |
| 52 | |
| 53 | def __init__(self, text, pipe_trigger): |
| 54 | # When sendall() is called with pipe_trigger, raise EPIPE. |
| 55 | FakeSocket.__init__(self, text) |
| 56 | self.pipe_trigger = pipe_trigger |
| 57 | |
| 58 | def sendall(self, data): |
| 59 | if self.pipe_trigger in data: |
| 60 | raise socket.error(errno.EPIPE, "gotcha") |
| 61 | self.data += data |
| 62 | |
| 63 | def close(self): |
| 64 | pass |
| 65 | |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 66 | class NoEOFStringIO(StringIO.StringIO): |
| 67 | """Like StringIO, but raises AssertionError on EOF. |
| 68 | |
| 69 | This is used below to test that httplib doesn't try to read |
| 70 | more from the underlying file than it should. |
| 71 | """ |
| 72 | def read(self, n=-1): |
| 73 | data = StringIO.StringIO.read(self, n) |
| 74 | if data == '': |
| 75 | raise AssertionError('caller tried to read past EOF') |
| 76 | return data |
| 77 | |
| 78 | def readline(self, length=None): |
| 79 | data = StringIO.StringIO.readline(self, length) |
| 80 | if data == '': |
| 81 | raise AssertionError('caller tried to read past EOF') |
| 82 | return data |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 83 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 84 | |
| 85 | class HeaderTests(TestCase): |
| 86 | def test_auto_headers(self): |
| 87 | # Some headers are added automatically, but should not be added by |
| 88 | # .request() if they are explicitly set. |
| 89 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 90 | class HeaderCountingBuffer(list): |
| 91 | def __init__(self): |
| 92 | self.count = {} |
| 93 | def append(self, item): |
| 94 | kv = item.split(':') |
| 95 | if len(kv) > 1: |
| 96 | # item is a 'Key: Value' header string |
| 97 | lcKey = kv[0].lower() |
| 98 | self.count.setdefault(lcKey, 0) |
| 99 | self.count[lcKey] += 1 |
| 100 | list.append(self, item) |
| 101 | |
| 102 | for explicit_header in True, False: |
| 103 | for header in 'Content-length', 'Host', 'Accept-encoding': |
| 104 | conn = httplib.HTTPConnection('example.com') |
| 105 | conn.sock = FakeSocket('blahblahblah') |
| 106 | conn._buffer = HeaderCountingBuffer() |
| 107 | |
| 108 | body = 'spamspamspam' |
| 109 | headers = {} |
| 110 | if explicit_header: |
| 111 | headers[header] = str(len(body)) |
| 112 | conn.request('POST', '/', body, headers) |
| 113 | self.assertEqual(conn._buffer.count[header.lower()], 1) |
| 114 | |
Senthil Kumaran | 618802d | 2012-05-19 16:52:21 +0800 | [diff] [blame] | 115 | def test_content_length_0(self): |
| 116 | |
| 117 | class ContentLengthChecker(list): |
| 118 | def __init__(self): |
| 119 | list.__init__(self) |
| 120 | self.content_length = None |
| 121 | def append(self, item): |
| 122 | kv = item.split(':', 1) |
| 123 | if len(kv) > 1 and kv[0].lower() == 'content-length': |
| 124 | self.content_length = kv[1].strip() |
| 125 | list.append(self, item) |
| 126 | |
R David Murray | b4b000f | 2015-03-22 15:15:44 -0400 | [diff] [blame] | 127 | # Here, we're testing that methods expecting a body get a |
| 128 | # content-length set to zero if the body is empty (either None or '') |
| 129 | bodies = (None, '') |
| 130 | methods_with_body = ('PUT', 'POST', 'PATCH') |
| 131 | for method, body in itertools.product(methods_with_body, bodies): |
| 132 | conn = httplib.HTTPConnection('example.com') |
| 133 | conn.sock = FakeSocket(None) |
| 134 | conn._buffer = ContentLengthChecker() |
| 135 | conn.request(method, '/', body) |
| 136 | self.assertEqual( |
| 137 | conn._buffer.content_length, '0', |
| 138 | 'Header Content-Length incorrect on {}'.format(method) |
| 139 | ) |
Senthil Kumaran | 618802d | 2012-05-19 16:52:21 +0800 | [diff] [blame] | 140 | |
R David Murray | b4b000f | 2015-03-22 15:15:44 -0400 | [diff] [blame] | 141 | # For these methods, we make sure that content-length is not set when |
| 142 | # the body is None because it might cause unexpected behaviour on the |
| 143 | # server. |
| 144 | methods_without_body = ( |
| 145 | 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE', |
| 146 | ) |
| 147 | for method in methods_without_body: |
| 148 | conn = httplib.HTTPConnection('example.com') |
| 149 | conn.sock = FakeSocket(None) |
| 150 | conn._buffer = ContentLengthChecker() |
| 151 | conn.request(method, '/', None) |
| 152 | self.assertEqual( |
| 153 | conn._buffer.content_length, None, |
| 154 | 'Header Content-Length set for empty body on {}'.format(method) |
| 155 | ) |
| 156 | |
| 157 | # If the body is set to '', that's considered to be "present but |
| 158 | # empty" rather than "missing", so content length would be set, even |
| 159 | # for methods that don't expect a body. |
| 160 | for method in methods_without_body: |
| 161 | conn = httplib.HTTPConnection('example.com') |
| 162 | conn.sock = FakeSocket(None) |
| 163 | conn._buffer = ContentLengthChecker() |
| 164 | conn.request(method, '/', '') |
| 165 | self.assertEqual( |
| 166 | conn._buffer.content_length, '0', |
| 167 | 'Header Content-Length incorrect on {}'.format(method) |
| 168 | ) |
| 169 | |
| 170 | # If the body is set, make sure Content-Length is set. |
| 171 | for method in itertools.chain(methods_without_body, methods_with_body): |
| 172 | conn = httplib.HTTPConnection('example.com') |
| 173 | conn.sock = FakeSocket(None) |
| 174 | conn._buffer = ContentLengthChecker() |
| 175 | conn.request(method, '/', ' ') |
| 176 | self.assertEqual( |
| 177 | conn._buffer.content_length, '1', |
| 178 | 'Header Content-Length incorrect on {}'.format(method) |
| 179 | ) |
Senthil Kumaran | 618802d | 2012-05-19 16:52:21 +0800 | [diff] [blame] | 180 | |
Senthil Kumaran | aa5f49e | 2010-10-03 18:26:07 +0000 | [diff] [blame] | 181 | def test_putheader(self): |
| 182 | conn = httplib.HTTPConnection('example.com') |
| 183 | conn.sock = FakeSocket(None) |
| 184 | conn.putrequest('GET','/') |
| 185 | conn.putheader('Content-length',42) |
Serhiy Storchaka | 528bed8 | 2014-02-08 14:49:55 +0200 | [diff] [blame] | 186 | self.assertIn('Content-length: 42', conn._buffer) |
Senthil Kumaran | aa5f49e | 2010-10-03 18:26:07 +0000 | [diff] [blame] | 187 | |
Serhiy Storchaka | 59bdf63 | 2015-03-12 11:12:51 +0200 | [diff] [blame] | 188 | conn.putheader('Foo', ' bar ') |
| 189 | self.assertIn(b'Foo: bar ', conn._buffer) |
| 190 | conn.putheader('Bar', '\tbaz\t') |
| 191 | self.assertIn(b'Bar: \tbaz\t', conn._buffer) |
| 192 | conn.putheader('Authorization', 'Bearer mytoken') |
| 193 | self.assertIn(b'Authorization: Bearer mytoken', conn._buffer) |
| 194 | conn.putheader('IterHeader', 'IterA', 'IterB') |
| 195 | self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer) |
| 196 | conn.putheader('LatinHeader', b'\xFF') |
| 197 | self.assertIn(b'LatinHeader: \xFF', conn._buffer) |
| 198 | conn.putheader('Utf8Header', b'\xc3\x80') |
| 199 | self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer) |
| 200 | conn.putheader('C1-Control', b'next\x85line') |
| 201 | self.assertIn(b'C1-Control: next\x85line', conn._buffer) |
| 202 | conn.putheader('Embedded-Fold-Space', 'is\r\n allowed') |
| 203 | self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer) |
| 204 | conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed') |
| 205 | self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer) |
| 206 | conn.putheader('Key Space', 'value') |
| 207 | self.assertIn(b'Key Space: value', conn._buffer) |
| 208 | conn.putheader('KeySpace ', 'value') |
| 209 | self.assertIn(b'KeySpace : value', conn._buffer) |
| 210 | conn.putheader(b'Nonbreak\xa0Space', 'value') |
| 211 | self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer) |
| 212 | conn.putheader(b'\xa0NonbreakSpace', 'value') |
| 213 | self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer) |
| 214 | |
Senthil Kumaran | 501bfd8 | 2010-11-14 03:31:52 +0000 | [diff] [blame] | 215 | def test_ipv6host_header(self): |
| 216 | # Default host header on IPv6 transaction should wrapped by [] if |
| 217 | # its actual IPv6 address |
| 218 | expected = 'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \ |
| 219 | 'Accept-Encoding: identity\r\n\r\n' |
| 220 | conn = httplib.HTTPConnection('[2001::]:81') |
| 221 | sock = FakeSocket('') |
| 222 | conn.sock = sock |
| 223 | conn.request('GET', '/foo') |
| 224 | self.assertTrue(sock.data.startswith(expected)) |
| 225 | |
| 226 | expected = 'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \ |
| 227 | 'Accept-Encoding: identity\r\n\r\n' |
| 228 | conn = httplib.HTTPConnection('[2001:102A::]') |
| 229 | sock = FakeSocket('') |
| 230 | conn.sock = sock |
| 231 | conn.request('GET', '/foo') |
| 232 | self.assertTrue(sock.data.startswith(expected)) |
| 233 | |
Benjamin Peterson | bfd976f | 2015-01-25 23:34:42 -0500 | [diff] [blame] | 234 | def test_malformed_headers_coped_with(self): |
| 235 | # Issue 19996 |
| 236 | body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n" |
| 237 | sock = FakeSocket(body) |
| 238 | resp = httplib.HTTPResponse(sock) |
| 239 | resp.begin() |
| 240 | |
| 241 | self.assertEqual(resp.getheader('First'), 'val') |
| 242 | self.assertEqual(resp.getheader('Second'), 'val') |
| 243 | |
Serhiy Storchaka | 59bdf63 | 2015-03-12 11:12:51 +0200 | [diff] [blame] | 244 | def test_invalid_headers(self): |
| 245 | conn = httplib.HTTPConnection('example.com') |
| 246 | conn.sock = FakeSocket('') |
| 247 | conn.putrequest('GET', '/') |
| 248 | |
| 249 | # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no |
| 250 | # longer allowed in header names |
| 251 | cases = ( |
| 252 | (b'Invalid\r\nName', b'ValidValue'), |
| 253 | (b'Invalid\rName', b'ValidValue'), |
| 254 | (b'Invalid\nName', b'ValidValue'), |
| 255 | (b'\r\nInvalidName', b'ValidValue'), |
| 256 | (b'\rInvalidName', b'ValidValue'), |
| 257 | (b'\nInvalidName', b'ValidValue'), |
| 258 | (b' InvalidName', b'ValidValue'), |
| 259 | (b'\tInvalidName', b'ValidValue'), |
| 260 | (b'Invalid:Name', b'ValidValue'), |
| 261 | (b':InvalidName', b'ValidValue'), |
| 262 | (b'ValidName', b'Invalid\r\nValue'), |
| 263 | (b'ValidName', b'Invalid\rValue'), |
| 264 | (b'ValidName', b'Invalid\nValue'), |
| 265 | (b'ValidName', b'InvalidValue\r\n'), |
| 266 | (b'ValidName', b'InvalidValue\r'), |
| 267 | (b'ValidName', b'InvalidValue\n'), |
| 268 | ) |
| 269 | for name, value in cases: |
| 270 | with self.assertRaisesRegexp(ValueError, 'Invalid header'): |
| 271 | conn.putheader(name, value) |
| 272 | |
Senthil Kumaran | 501bfd8 | 2010-11-14 03:31:52 +0000 | [diff] [blame] | 273 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 274 | class BasicTest(TestCase): |
| 275 | def test_status_lines(self): |
| 276 | # Test HTTP status lines |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 277 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 278 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 279 | sock = FakeSocket(body) |
| 280 | resp = httplib.HTTPResponse(sock) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 281 | resp.begin() |
Serhiy Storchaka | c97f5ed | 2013-12-17 21:49:48 +0200 | [diff] [blame] | 282 | self.assertEqual(resp.read(0), '') # Issue #20007 |
| 283 | self.assertFalse(resp.isclosed()) |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 284 | self.assertEqual(resp.read(), 'Text') |
Facundo Batista | 7066590 | 2007-10-18 03:16:03 +0000 | [diff] [blame] | 285 | self.assertTrue(resp.isclosed()) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 286 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 287 | body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" |
| 288 | sock = FakeSocket(body) |
| 289 | resp = httplib.HTTPResponse(sock) |
| 290 | self.assertRaises(httplib.BadStatusLine, resp.begin) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 291 | |
Dirkjan Ochtman | ebc73dc | 2010-02-24 04:49:00 +0000 | [diff] [blame] | 292 | def test_bad_status_repr(self): |
| 293 | exc = httplib.BadStatusLine('') |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 294 | self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''') |
Dirkjan Ochtman | ebc73dc | 2010-02-24 04:49:00 +0000 | [diff] [blame] | 295 | |
Facundo Batista | 7066590 | 2007-10-18 03:16:03 +0000 | [diff] [blame] | 296 | def test_partial_reads(self): |
Antoine Pitrou | 4113d2b | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 297 | # if we have a length, the system knows when to close itself |
Facundo Batista | 7066590 | 2007-10-18 03:16:03 +0000 | [diff] [blame] | 298 | # same behaviour than when we read the whole thing with read() |
| 299 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" |
| 300 | sock = FakeSocket(body) |
| 301 | resp = httplib.HTTPResponse(sock) |
| 302 | resp.begin() |
| 303 | self.assertEqual(resp.read(2), 'Te') |
| 304 | self.assertFalse(resp.isclosed()) |
| 305 | self.assertEqual(resp.read(2), 'xt') |
| 306 | self.assertTrue(resp.isclosed()) |
| 307 | |
Antoine Pitrou | 4113d2b | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 308 | def test_partial_reads_no_content_length(self): |
| 309 | # when no length is present, the socket should be gracefully closed when |
| 310 | # all data was read |
| 311 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 312 | sock = FakeSocket(body) |
| 313 | resp = httplib.HTTPResponse(sock) |
| 314 | resp.begin() |
| 315 | self.assertEqual(resp.read(2), 'Te') |
| 316 | self.assertFalse(resp.isclosed()) |
| 317 | self.assertEqual(resp.read(2), 'xt') |
| 318 | self.assertEqual(resp.read(1), '') |
| 319 | self.assertTrue(resp.isclosed()) |
| 320 | |
Antoine Pitrou | d66c0ee | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 321 | def test_partial_reads_incomplete_body(self): |
| 322 | # if the server shuts down the connection before the whole |
| 323 | # content-length is delivered, the socket is gracefully closed |
| 324 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" |
| 325 | sock = FakeSocket(body) |
| 326 | resp = httplib.HTTPResponse(sock) |
| 327 | resp.begin() |
| 328 | self.assertEqual(resp.read(2), 'Te') |
| 329 | self.assertFalse(resp.isclosed()) |
| 330 | self.assertEqual(resp.read(2), 'xt') |
| 331 | self.assertEqual(resp.read(1), '') |
| 332 | self.assertTrue(resp.isclosed()) |
| 333 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 334 | def test_host_port(self): |
| 335 | # Check invalid host_port |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 336 | |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 337 | # Note that httplib does not accept user:password@ in the host-port. |
| 338 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 339 | self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp) |
| 340 | |
Jeremy Hylton | 21d2e59 | 2008-11-29 00:09:16 +0000 | [diff] [blame] | 341 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", |
| 342 | 8000), |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 343 | ("www.python.org:80", "www.python.org", 80), |
| 344 | ("www.python.org", "www.python.org", 80), |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 345 | ("www.python.org:", "www.python.org", 80), |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 346 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)): |
Martin v. Löwis | 74a249e | 2004-09-14 21:45:36 +0000 | [diff] [blame] | 347 | http = httplib.HTTP(hp) |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 348 | c = http._conn |
Jeremy Hylton | 21d2e59 | 2008-11-29 00:09:16 +0000 | [diff] [blame] | 349 | if h != c.host: |
| 350 | self.fail("Host incorrectly parsed: %s != %s" % (h, c.host)) |
| 351 | if p != c.port: |
| 352 | self.fail("Port incorrectly parsed: %s != %s" % (p, c.host)) |
Skip Montanaro | 10e6e0e | 2004-09-14 16:32:02 +0000 | [diff] [blame] | 353 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 354 | def test_response_headers(self): |
| 355 | # test response with multiple message headers with the same field name. |
| 356 | text = ('HTTP/1.1 200 OK\r\n' |
Jeremy Hylton | 21d2e59 | 2008-11-29 00:09:16 +0000 | [diff] [blame] | 357 | 'Set-Cookie: Customer="WILE_E_COYOTE";' |
| 358 | ' Version="1"; Path="/acme"\r\n' |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 359 | 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' |
| 360 | ' Path="/acme"\r\n' |
| 361 | '\r\n' |
| 362 | 'No body\r\n') |
| 363 | hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' |
| 364 | ', ' |
| 365 | 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') |
| 366 | s = FakeSocket(text) |
| 367 | r = httplib.HTTPResponse(s) |
| 368 | r.begin() |
| 369 | cookies = r.getheader("Set-Cookie") |
| 370 | if cookies != hdr: |
| 371 | self.fail("multiple headers not combined properly") |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 372 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 373 | def test_read_head(self): |
| 374 | # Test that the library doesn't attempt to read any data |
| 375 | # from a HEAD request. (Tickles SF bug #622042.) |
| 376 | sock = FakeSocket( |
| 377 | 'HTTP/1.1 200 OK\r\n' |
| 378 | 'Content-Length: 14432\r\n' |
| 379 | '\r\n', |
| 380 | NoEOFStringIO) |
| 381 | resp = httplib.HTTPResponse(sock, method="HEAD") |
| 382 | resp.begin() |
| 383 | if resp.read() != "": |
| 384 | self.fail("Did not expect response from HEAD request") |
Jeremy Hylton | c1b2cb9 | 2003-05-05 16:13:58 +0000 | [diff] [blame] | 385 | |
Berker Peksag | b7414e0 | 2014-08-05 07:15:57 +0300 | [diff] [blame] | 386 | def test_too_many_headers(self): |
| 387 | headers = '\r\n'.join('Header%d: foo' % i for i in xrange(200)) + '\r\n' |
| 388 | text = ('HTTP/1.1 200 OK\r\n' + headers) |
| 389 | s = FakeSocket(text) |
| 390 | r = httplib.HTTPResponse(s) |
| 391 | self.assertRaises(httplib.HTTPException, r.begin) |
| 392 | |
Martin v. Löwis | 040a927 | 2006-11-12 10:32:47 +0000 | [diff] [blame] | 393 | def test_send_file(self): |
| 394 | expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ |
| 395 | 'Accept-Encoding: identity\r\nContent-Length:' |
| 396 | |
| 397 | body = open(__file__, 'rb') |
| 398 | conn = httplib.HTTPConnection('example.com') |
| 399 | sock = FakeSocket(body) |
| 400 | conn.sock = sock |
| 401 | conn.request('GET', '/foo', body) |
| 402 | self.assertTrue(sock.data.startswith(expected)) |
Serhiy Storchaka | 80573bb | 2015-05-16 18:58:41 +0300 | [diff] [blame] | 403 | self.assertIn('def test_send_file', sock.data) |
| 404 | |
| 405 | def test_send_tempfile(self): |
| 406 | expected = ('GET /foo HTTP/1.1\r\nHost: example.com\r\n' |
| 407 | 'Accept-Encoding: identity\r\nContent-Length: 9\r\n\r\n' |
| 408 | 'fake\ndata') |
| 409 | |
| 410 | with tempfile.TemporaryFile() as body: |
| 411 | body.write('fake\ndata') |
| 412 | body.seek(0) |
| 413 | |
| 414 | conn = httplib.HTTPConnection('example.com') |
| 415 | sock = FakeSocket(body) |
| 416 | conn.sock = sock |
| 417 | conn.request('GET', '/foo', body) |
| 418 | self.assertEqual(sock.data, expected) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 419 | |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 420 | def test_send(self): |
| 421 | expected = 'this is a test this is only a test' |
| 422 | conn = httplib.HTTPConnection('example.com') |
| 423 | sock = FakeSocket(None) |
| 424 | conn.sock = sock |
| 425 | conn.send(expected) |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 426 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 427 | sock.data = '' |
| 428 | conn.send(array.array('c', expected)) |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 429 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 430 | sock.data = '' |
| 431 | conn.send(StringIO.StringIO(expected)) |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 432 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | 7248178 | 2009-09-29 17:48:18 +0000 | [diff] [blame] | 433 | |
Georg Brandl | 2363503 | 2008-02-24 00:03:22 +0000 | [diff] [blame] | 434 | def test_chunked(self): |
| 435 | chunked_start = ( |
| 436 | 'HTTP/1.1 200 OK\r\n' |
| 437 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 438 | 'a\r\n' |
| 439 | 'hello worl\r\n' |
| 440 | '1\r\n' |
| 441 | 'd\r\n' |
| 442 | ) |
| 443 | sock = FakeSocket(chunked_start + '0\r\n') |
| 444 | resp = httplib.HTTPResponse(sock, method="GET") |
| 445 | resp.begin() |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 446 | self.assertEqual(resp.read(), 'hello world') |
Georg Brandl | 2363503 | 2008-02-24 00:03:22 +0000 | [diff] [blame] | 447 | resp.close() |
| 448 | |
| 449 | for x in ('', 'foo\r\n'): |
| 450 | sock = FakeSocket(chunked_start + x) |
| 451 | resp = httplib.HTTPResponse(sock, method="GET") |
| 452 | resp.begin() |
| 453 | try: |
| 454 | resp.read() |
| 455 | except httplib.IncompleteRead, i: |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 456 | self.assertEqual(i.partial, 'hello world') |
Benjamin Peterson | 7d49bba | 2009-03-02 22:41:42 +0000 | [diff] [blame] | 457 | self.assertEqual(repr(i),'IncompleteRead(11 bytes read)') |
| 458 | self.assertEqual(str(i),'IncompleteRead(11 bytes read)') |
Georg Brandl | 2363503 | 2008-02-24 00:03:22 +0000 | [diff] [blame] | 459 | else: |
| 460 | self.fail('IncompleteRead expected') |
| 461 | finally: |
| 462 | resp.close() |
| 463 | |
Senthil Kumaran | ed920434 | 2010-04-28 17:20:43 +0000 | [diff] [blame] | 464 | def test_chunked_head(self): |
| 465 | chunked_start = ( |
| 466 | 'HTTP/1.1 200 OK\r\n' |
| 467 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 468 | 'a\r\n' |
| 469 | 'hello world\r\n' |
| 470 | '1\r\n' |
| 471 | 'd\r\n' |
| 472 | ) |
| 473 | sock = FakeSocket(chunked_start + '0\r\n') |
| 474 | resp = httplib.HTTPResponse(sock, method="HEAD") |
| 475 | resp.begin() |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 476 | self.assertEqual(resp.read(), '') |
| 477 | self.assertEqual(resp.status, 200) |
| 478 | self.assertEqual(resp.reason, 'OK') |
Senthil Kumaran | fb69501 | 2010-06-04 17:17:09 +0000 | [diff] [blame] | 479 | self.assertTrue(resp.isclosed()) |
Senthil Kumaran | ed920434 | 2010-04-28 17:20:43 +0000 | [diff] [blame] | 480 | |
Georg Brandl | 8c460d5 | 2008-02-24 00:14:24 +0000 | [diff] [blame] | 481 | def test_negative_content_length(self): |
Jeremy Hylton | 21d2e59 | 2008-11-29 00:09:16 +0000 | [diff] [blame] | 482 | sock = FakeSocket('HTTP/1.1 200 OK\r\n' |
| 483 | 'Content-Length: -1\r\n\r\nHello\r\n') |
Georg Brandl | 8c460d5 | 2008-02-24 00:14:24 +0000 | [diff] [blame] | 484 | resp = httplib.HTTPResponse(sock, method="GET") |
| 485 | resp.begin() |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 486 | self.assertEqual(resp.read(), 'Hello\r\n') |
Antoine Pitrou | d66c0ee | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 487 | self.assertTrue(resp.isclosed()) |
Georg Brandl | 8c460d5 | 2008-02-24 00:14:24 +0000 | [diff] [blame] | 488 | |
Benjamin Peterson | 7d49bba | 2009-03-02 22:41:42 +0000 | [diff] [blame] | 489 | def test_incomplete_read(self): |
| 490 | sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n') |
| 491 | resp = httplib.HTTPResponse(sock, method="GET") |
| 492 | resp.begin() |
| 493 | try: |
| 494 | resp.read() |
| 495 | except httplib.IncompleteRead as i: |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 496 | self.assertEqual(i.partial, 'Hello\r\n') |
Benjamin Peterson | 7d49bba | 2009-03-02 22:41:42 +0000 | [diff] [blame] | 497 | self.assertEqual(repr(i), |
| 498 | "IncompleteRead(7 bytes read, 3 more expected)") |
| 499 | self.assertEqual(str(i), |
| 500 | "IncompleteRead(7 bytes read, 3 more expected)") |
Antoine Pitrou | d66c0ee | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 501 | self.assertTrue(resp.isclosed()) |
Benjamin Peterson | 7d49bba | 2009-03-02 22:41:42 +0000 | [diff] [blame] | 502 | else: |
| 503 | self.fail('IncompleteRead expected') |
Benjamin Peterson | 7d49bba | 2009-03-02 22:41:42 +0000 | [diff] [blame] | 504 | |
Victor Stinner | 2c6aee9 | 2010-07-24 02:46:16 +0000 | [diff] [blame] | 505 | def test_epipe(self): |
| 506 | sock = EPipeSocket( |
| 507 | "HTTP/1.0 401 Authorization Required\r\n" |
| 508 | "Content-type: text/html\r\n" |
| 509 | "WWW-Authenticate: Basic realm=\"example\"\r\n", |
| 510 | b"Content-Length") |
| 511 | conn = httplib.HTTPConnection("example.com") |
| 512 | conn.sock = sock |
| 513 | self.assertRaises(socket.error, |
| 514 | lambda: conn.request("PUT", "/url", "body")) |
| 515 | resp = conn.getresponse() |
| 516 | self.assertEqual(401, resp.status) |
| 517 | self.assertEqual("Basic realm=\"example\"", |
| 518 | resp.getheader("www-authenticate")) |
| 519 | |
Senthil Kumaran | d389cb5 | 2010-09-21 01:38:15 +0000 | [diff] [blame] | 520 | def test_filenoattr(self): |
| 521 | # Just test the fileno attribute in the HTTPResponse Object. |
| 522 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 523 | sock = FakeSocket(body) |
| 524 | resp = httplib.HTTPResponse(sock) |
| 525 | self.assertTrue(hasattr(resp,'fileno'), |
| 526 | 'HTTPResponse should expose a fileno attribute') |
Georg Brandl | 2363503 | 2008-02-24 00:03:22 +0000 | [diff] [blame] | 527 | |
Antoine Pitrou | d7b6ac6 | 2010-12-18 18:18:21 +0000 | [diff] [blame] | 528 | # Test lines overflowing the max line size (_MAXLINE in http.client) |
| 529 | |
| 530 | def test_overflowing_status_line(self): |
| 531 | self.skipTest("disabled for HTTP 0.9 support") |
| 532 | body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n" |
| 533 | resp = httplib.HTTPResponse(FakeSocket(body)) |
| 534 | self.assertRaises((httplib.LineTooLong, httplib.BadStatusLine), resp.begin) |
| 535 | |
| 536 | def test_overflowing_header_line(self): |
| 537 | body = ( |
| 538 | 'HTTP/1.1 200 OK\r\n' |
| 539 | 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n' |
| 540 | ) |
| 541 | resp = httplib.HTTPResponse(FakeSocket(body)) |
| 542 | self.assertRaises(httplib.LineTooLong, resp.begin) |
| 543 | |
| 544 | def test_overflowing_chunked_line(self): |
| 545 | body = ( |
| 546 | 'HTTP/1.1 200 OK\r\n' |
| 547 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 548 | + '0' * 65536 + 'a\r\n' |
| 549 | 'hello world\r\n' |
| 550 | '0\r\n' |
| 551 | ) |
| 552 | resp = httplib.HTTPResponse(FakeSocket(body)) |
| 553 | resp.begin() |
| 554 | self.assertRaises(httplib.LineTooLong, resp.read) |
| 555 | |
Senthil Kumaran | f5aaf6f | 2012-04-29 10:15:31 +0800 | [diff] [blame] | 556 | def test_early_eof(self): |
| 557 | # Test httpresponse with no \r\n termination, |
| 558 | body = "HTTP/1.1 200 Ok" |
| 559 | sock = FakeSocket(body) |
| 560 | resp = httplib.HTTPResponse(sock) |
| 561 | resp.begin() |
| 562 | self.assertEqual(resp.read(), '') |
| 563 | self.assertTrue(resp.isclosed()) |
Antoine Pitrou | d7b6ac6 | 2010-12-18 18:18:21 +0000 | [diff] [blame] | 564 | |
Serhiy Storchaka | d862db0 | 2014-12-01 13:07:28 +0200 | [diff] [blame] | 565 | def test_error_leak(self): |
| 566 | # Test that the socket is not leaked if getresponse() fails |
| 567 | conn = httplib.HTTPConnection('example.com') |
| 568 | response = [] |
| 569 | class Response(httplib.HTTPResponse): |
| 570 | def __init__(self, *pos, **kw): |
| 571 | response.append(self) # Avoid garbage collector closing the socket |
| 572 | httplib.HTTPResponse.__init__(self, *pos, **kw) |
| 573 | conn.response_class = Response |
| 574 | conn.sock = FakeSocket('') # Emulate server dropping connection |
| 575 | conn.request('GET', '/') |
| 576 | self.assertRaises(httplib.BadStatusLine, conn.getresponse) |
| 577 | self.assertTrue(response) |
| 578 | #self.assertTrue(response[0].closed) |
| 579 | self.assertTrue(conn.sock.file_closed) |
| 580 | |
Martin Panter | b75a0e9 | 2015-09-07 01:18:47 +0000 | [diff] [blame] | 581 | def test_proxy_tunnel_without_status_line(self): |
| 582 | # Issue 17849: If a proxy tunnel is created that does not return |
| 583 | # a status code, fail. |
| 584 | body = 'hello world' |
| 585 | conn = httplib.HTTPConnection('example.com', strict=False) |
| 586 | conn.set_tunnel('foo') |
| 587 | conn.sock = FakeSocket(body) |
| 588 | with self.assertRaisesRegexp(socket.error, "Invalid response"): |
| 589 | conn._tunnel() |
| 590 | |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 591 | class OfflineTest(TestCase): |
| 592 | def test_responses(self): |
Ezio Melotti | 2623a37 | 2010-11-21 13:34:58 +0000 | [diff] [blame] | 593 | self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found") |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 594 | |
Gregory P. Smith | 9d32521 | 2010-01-03 02:06:07 +0000 | [diff] [blame] | 595 | |
Senthil Kumaran | 812b975 | 2015-01-24 12:58:10 -0800 | [diff] [blame] | 596 | class TestServerMixin: |
| 597 | """A limited socket server mixin. |
| 598 | |
| 599 | This is used by test cases for testing http connection end points. |
| 600 | """ |
Gregory P. Smith | 9d32521 | 2010-01-03 02:06:07 +0000 | [diff] [blame] | 601 | def setUp(self): |
| 602 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 603 | self.port = test_support.bind_port(self.serv) |
| 604 | self.source_port = test_support.find_unused_port() |
| 605 | self.serv.listen(5) |
| 606 | self.conn = None |
| 607 | |
| 608 | def tearDown(self): |
| 609 | if self.conn: |
| 610 | self.conn.close() |
| 611 | self.conn = None |
| 612 | self.serv.close() |
| 613 | self.serv = None |
| 614 | |
Senthil Kumaran | 812b975 | 2015-01-24 12:58:10 -0800 | [diff] [blame] | 615 | class SourceAddressTest(TestServerMixin, TestCase): |
Gregory P. Smith | 9d32521 | 2010-01-03 02:06:07 +0000 | [diff] [blame] | 616 | def testHTTPConnectionSourceAddress(self): |
| 617 | self.conn = httplib.HTTPConnection(HOST, self.port, |
| 618 | source_address=('', self.source_port)) |
| 619 | self.conn.connect() |
| 620 | self.assertEqual(self.conn.sock.getsockname()[1], self.source_port) |
| 621 | |
| 622 | @unittest.skipIf(not hasattr(httplib, 'HTTPSConnection'), |
| 623 | 'httplib.HTTPSConnection not defined') |
| 624 | def testHTTPSConnectionSourceAddress(self): |
| 625 | self.conn = httplib.HTTPSConnection(HOST, self.port, |
| 626 | source_address=('', self.source_port)) |
| 627 | # We don't test anything here other the constructor not barfing as |
| 628 | # this code doesn't deal with setting up an active running SSL server |
| 629 | # for an ssl_wrapped connect() to actually return from. |
| 630 | |
| 631 | |
Senthil Kumaran | 812b975 | 2015-01-24 12:58:10 -0800 | [diff] [blame] | 632 | class HTTPTest(TestServerMixin, TestCase): |
| 633 | def testHTTPConnection(self): |
| 634 | self.conn = httplib.HTTP(host=HOST, port=self.port, strict=None) |
| 635 | self.conn.connect() |
| 636 | self.assertEqual(self.conn._conn.host, HOST) |
| 637 | self.assertEqual(self.conn._conn.port, self.port) |
| 638 | |
| 639 | def testHTTPWithConnectHostPort(self): |
| 640 | testhost = 'unreachable.test.domain' |
| 641 | testport = '80' |
| 642 | self.conn = httplib.HTTP(host=testhost, port=testport) |
| 643 | self.conn.connect(host=HOST, port=self.port) |
| 644 | self.assertNotEqual(self.conn._conn.host, testhost) |
| 645 | self.assertNotEqual(self.conn._conn.port, testport) |
| 646 | self.assertEqual(self.conn._conn.host, HOST) |
| 647 | self.assertEqual(self.conn._conn.port, self.port) |
| 648 | |
| 649 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 650 | class TimeoutTest(TestCase): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 651 | PORT = None |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 652 | |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 653 | def setUp(self): |
| 654 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Trent Nelson | 6c4a7c6 | 2008-04-09 00:34:53 +0000 | [diff] [blame] | 655 | TimeoutTest.PORT = test_support.bind_port(self.serv) |
Facundo Batista | f196629 | 2007-03-25 03:20:05 +0000 | [diff] [blame] | 656 | self.serv.listen(5) |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 657 | |
| 658 | def tearDown(self): |
| 659 | self.serv.close() |
| 660 | self.serv = None |
| 661 | |
| 662 | def testTimeoutAttribute(self): |
| 663 | '''This will prove that the timeout gets through |
| 664 | HTTPConnection and into the socket. |
| 665 | ''' |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 666 | # default -- use global socket timeout |
Serhiy Storchaka | 528bed8 | 2014-02-08 14:49:55 +0200 | [diff] [blame] | 667 | self.assertIsNone(socket.getdefaulttimeout()) |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 668 | socket.setdefaulttimeout(30) |
| 669 | try: |
| 670 | httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) |
| 671 | httpConn.connect() |
| 672 | finally: |
| 673 | socket.setdefaulttimeout(None) |
Facundo Batista | 14553b0 | 2007-03-23 20:23:08 +0000 | [diff] [blame] | 674 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
Facundo Batista | f196629 | 2007-03-25 03:20:05 +0000 | [diff] [blame] | 675 | httpConn.close() |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 676 | |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 677 | # no timeout -- do not use global socket default |
Serhiy Storchaka | 528bed8 | 2014-02-08 14:49:55 +0200 | [diff] [blame] | 678 | self.assertIsNone(socket.getdefaulttimeout()) |
Facundo Batista | 14553b0 | 2007-03-23 20:23:08 +0000 | [diff] [blame] | 679 | socket.setdefaulttimeout(30) |
| 680 | try: |
Trent Nelson | 6c4a7c6 | 2008-04-09 00:34:53 +0000 | [diff] [blame] | 681 | httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, |
| 682 | timeout=None) |
Facundo Batista | 14553b0 | 2007-03-23 20:23:08 +0000 | [diff] [blame] | 683 | httpConn.connect() |
| 684 | finally: |
Facundo Batista | 4f1b1ed | 2008-05-29 16:39:26 +0000 | [diff] [blame] | 685 | socket.setdefaulttimeout(None) |
| 686 | self.assertEqual(httpConn.sock.gettimeout(), None) |
| 687 | httpConn.close() |
| 688 | |
| 689 | # a value |
| 690 | httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) |
| 691 | httpConn.connect() |
Facundo Batista | 14553b0 | 2007-03-23 20:23:08 +0000 | [diff] [blame] | 692 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
Facundo Batista | f196629 | 2007-03-25 03:20:05 +0000 | [diff] [blame] | 693 | httpConn.close() |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 694 | |
Senthil Kumaran | 812b975 | 2015-01-24 12:58:10 -0800 | [diff] [blame] | 695 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 696 | class HTTPSTest(TestCase): |
Facundo Batista | 07c78be | 2007-03-23 18:54:07 +0000 | [diff] [blame] | 697 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 698 | def setUp(self): |
| 699 | if not hasattr(httplib, 'HTTPSConnection'): |
| 700 | self.skipTest('ssl support required') |
| 701 | |
| 702 | def make_server(self, certfile): |
| 703 | from test.ssl_servers import make_https_server |
| 704 | return make_https_server(self, certfile=certfile) |
Facundo Batista | 70f996b | 2007-05-21 17:32:32 +0000 | [diff] [blame] | 705 | |
| 706 | def test_attributes(self): |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 707 | # simple test to check it's storing the timeout |
| 708 | h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) |
| 709 | self.assertEqual(h.timeout, 30) |
Facundo Batista | 70f996b | 2007-05-21 17:32:32 +0000 | [diff] [blame] | 710 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 711 | def test_networked(self): |
| 712 | # Default settings: requires a valid cert from a trusted CA |
| 713 | import ssl |
| 714 | test_support.requires('network') |
| 715 | with test_support.transient_internet('self-signed.pythontest.net'): |
| 716 | h = httplib.HTTPSConnection('self-signed.pythontest.net', 443) |
| 717 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 718 | h.request('GET', '/') |
| 719 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 720 | |
| 721 | def test_networked_noverification(self): |
| 722 | # Switch off cert verification |
| 723 | import ssl |
| 724 | test_support.requires('network') |
| 725 | with test_support.transient_internet('self-signed.pythontest.net'): |
| 726 | context = ssl._create_stdlib_context() |
| 727 | h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, |
| 728 | context=context) |
| 729 | h.request('GET', '/') |
| 730 | resp = h.getresponse() |
| 731 | self.assertIn('nginx', resp.getheader('server')) |
| 732 | |
Benjamin Peterson | f671de4 | 2014-11-25 15:16:55 -0600 | [diff] [blame] | 733 | @test_support.system_must_validate_cert |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 734 | def test_networked_trusted_by_default_cert(self): |
| 735 | # Default settings: requires a valid cert from a trusted CA |
| 736 | test_support.requires('network') |
| 737 | with test_support.transient_internet('www.python.org'): |
| 738 | h = httplib.HTTPSConnection('www.python.org', 443) |
| 739 | h.request('GET', '/') |
| 740 | resp = h.getresponse() |
| 741 | content_type = resp.getheader('content-type') |
| 742 | self.assertIn('text/html', content_type) |
| 743 | |
| 744 | def test_networked_good_cert(self): |
| 745 | # We feed the server's cert as a validating cert |
| 746 | import ssl |
| 747 | test_support.requires('network') |
| 748 | with test_support.transient_internet('self-signed.pythontest.net'): |
| 749 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 750 | context.verify_mode = ssl.CERT_REQUIRED |
| 751 | context.load_verify_locations(CERT_selfsigned_pythontestdotnet) |
| 752 | h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
| 753 | h.request('GET', '/') |
| 754 | resp = h.getresponse() |
| 755 | server_string = resp.getheader('server') |
| 756 | self.assertIn('nginx', server_string) |
| 757 | |
| 758 | def test_networked_bad_cert(self): |
| 759 | # We feed a "CA" cert that is unrelated to the server's cert |
| 760 | import ssl |
| 761 | test_support.requires('network') |
| 762 | with test_support.transient_internet('self-signed.pythontest.net'): |
| 763 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 764 | context.verify_mode = ssl.CERT_REQUIRED |
| 765 | context.load_verify_locations(CERT_localhost) |
| 766 | h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
| 767 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 768 | h.request('GET', '/') |
| 769 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 770 | |
| 771 | def test_local_unknown_cert(self): |
| 772 | # The custom cert isn't known to the default trust bundle |
| 773 | import ssl |
| 774 | server = self.make_server(CERT_localhost) |
| 775 | h = httplib.HTTPSConnection('localhost', server.port) |
| 776 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 777 | h.request('GET', '/') |
| 778 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 779 | |
| 780 | def test_local_good_hostname(self): |
| 781 | # The (valid) cert validates the HTTP hostname |
| 782 | import ssl |
| 783 | server = self.make_server(CERT_localhost) |
| 784 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 785 | context.verify_mode = ssl.CERT_REQUIRED |
| 786 | context.load_verify_locations(CERT_localhost) |
| 787 | h = httplib.HTTPSConnection('localhost', server.port, context=context) |
| 788 | h.request('GET', '/nonexistent') |
| 789 | resp = h.getresponse() |
| 790 | self.assertEqual(resp.status, 404) |
| 791 | |
| 792 | def test_local_bad_hostname(self): |
| 793 | # The (valid) cert doesn't validate the HTTP hostname |
| 794 | import ssl |
| 795 | server = self.make_server(CERT_fakehostname) |
| 796 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 797 | context.verify_mode = ssl.CERT_REQUIRED |
Benjamin Peterson | 227f6e0 | 2014-12-07 13:41:26 -0500 | [diff] [blame] | 798 | context.check_hostname = True |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 799 | context.load_verify_locations(CERT_fakehostname) |
| 800 | h = httplib.HTTPSConnection('localhost', server.port, context=context) |
| 801 | with self.assertRaises(ssl.CertificateError): |
| 802 | h.request('GET', '/') |
Benjamin Peterson | 227f6e0 | 2014-12-07 13:41:26 -0500 | [diff] [blame] | 803 | h.close() |
| 804 | # With context.check_hostname=False, the mismatching is ignored |
| 805 | context.check_hostname = False |
| 806 | h = httplib.HTTPSConnection('localhost', server.port, context=context) |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 807 | h.request('GET', '/nonexistent') |
| 808 | resp = h.getresponse() |
| 809 | self.assertEqual(resp.status, 404) |
| 810 | |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 811 | def test_host_port(self): |
| 812 | # Check invalid host_port |
| 813 | |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 814 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 815 | self.assertRaises(httplib.InvalidURL, httplib.HTTPSConnection, hp) |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 816 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 817 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", |
| 818 | "fe80::207:e9ff:fe9b", 8000), |
| 819 | ("www.python.org:443", "www.python.org", 443), |
| 820 | ("www.python.org:", "www.python.org", 443), |
| 821 | ("www.python.org", "www.python.org", 443), |
| 822 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443), |
| 823 | ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", |
| 824 | 443)): |
| 825 | c = httplib.HTTPSConnection(hp) |
| 826 | self.assertEqual(h, c.host) |
| 827 | self.assertEqual(p, c.port) |
Łukasz Langa | 7a15390 | 2011-10-18 17:16:00 +0200 | [diff] [blame] | 828 | |
| 829 | |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 830 | class TunnelTests(TestCase): |
| 831 | def test_connect(self): |
| 832 | response_text = ( |
| 833 | 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT |
| 834 | 'HTTP/1.1 200 OK\r\n' # Reply to HEAD |
| 835 | 'Content-Length: 42\r\n\r\n' |
| 836 | ) |
| 837 | |
| 838 | def create_connection(address, timeout=None, source_address=None): |
| 839 | return FakeSocket(response_text, host=address[0], port=address[1]) |
| 840 | |
| 841 | conn = httplib.HTTPConnection('proxy.com') |
| 842 | conn._create_connection = create_connection |
| 843 | |
| 844 | # Once connected, we should not be able to tunnel anymore |
| 845 | conn.connect() |
| 846 | self.assertRaises(RuntimeError, conn.set_tunnel, 'destination.com') |
| 847 | |
| 848 | # But if close the connection, we are good. |
| 849 | conn.close() |
| 850 | conn.set_tunnel('destination.com') |
| 851 | conn.request('HEAD', '/', '') |
| 852 | |
| 853 | self.assertEqual(conn.sock.host, 'proxy.com') |
| 854 | self.assertEqual(conn.sock.port, 80) |
Serhiy Storchaka | 9d1de8a | 2015-05-28 22:37:13 +0300 | [diff] [blame] | 855 | self.assertIn('CONNECT destination.com', conn.sock.data) |
| 856 | # issue22095 |
| 857 | self.assertNotIn('Host: destination.com:None', conn.sock.data) |
| 858 | self.assertIn('Host: destination.com', conn.sock.data) |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 859 | |
Serhiy Storchaka | 9d1de8a | 2015-05-28 22:37:13 +0300 | [diff] [blame] | 860 | self.assertNotIn('Host: proxy.com', conn.sock.data) |
Senthil Kumaran | 36f28f7 | 2014-05-16 18:51:46 -0700 | [diff] [blame] | 861 | |
| 862 | conn.close() |
| 863 | |
| 864 | conn.request('PUT', '/', '') |
| 865 | self.assertEqual(conn.sock.host, 'proxy.com') |
| 866 | self.assertEqual(conn.sock.port, 80) |
| 867 | self.assertTrue('CONNECT destination.com' in conn.sock.data) |
| 868 | self.assertTrue('Host: destination.com' in conn.sock.data) |
| 869 | |
| 870 | |
Benjamin Peterson | fcfb18e | 2014-11-23 11:42:45 -0600 | [diff] [blame] | 871 | @test_support.reap_threads |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 872 | def test_main(verbose=None): |
Trent Nelson | e41b006 | 2008-04-08 23:47:30 +0000 | [diff] [blame] | 873 | test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, |
Senthil Kumaran | 812b975 | 2015-01-24 12:58:10 -0800 | [diff] [blame] | 874 | HTTPTest, HTTPSTest, SourceAddressTest, |
| 875 | TunnelTests) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 876 | |
Georg Brandl | 71a2089 | 2006-10-29 20:24:01 +0000 | [diff] [blame] | 877 | if __name__ == '__main__': |
| 878 | test_main() |