Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 1 | import errno |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 2 | from http import client |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 3 | import io |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 4 | import itertools |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 5 | import os |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 6 | import array |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 7 | import socket |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 8 | |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 9 | import unittest |
| 10 | TestCase = unittest.TestCase |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 11 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 12 | from test import support |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 13 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 14 | here = os.path.dirname(__file__) |
| 15 | # Self-signed cert file for 'localhost' |
| 16 | CERT_localhost = os.path.join(here, 'keycert.pem') |
| 17 | # Self-signed cert file for 'fakehostname' |
| 18 | CERT_fakehostname = os.path.join(here, 'keycert2.pem') |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 19 | # Self-signed cert file for self-signed.pythontest.net |
| 20 | CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 21 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 22 | # constants for testing chunked encoding |
| 23 | chunked_start = ( |
| 24 | 'HTTP/1.1 200 OK\r\n' |
| 25 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 26 | 'a\r\n' |
| 27 | 'hello worl\r\n' |
| 28 | '3\r\n' |
| 29 | 'd! \r\n' |
| 30 | '8\r\n' |
| 31 | 'and now \r\n' |
| 32 | '22\r\n' |
| 33 | 'for something completely different\r\n' |
| 34 | ) |
| 35 | chunked_expected = b'hello world! and now for something completely different' |
| 36 | chunk_extension = ";foo=bar" |
| 37 | last_chunk = "0\r\n" |
| 38 | last_chunk_extended = "0" + chunk_extension + "\r\n" |
| 39 | trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n" |
| 40 | chunked_end = "\r\n" |
| 41 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 42 | HOST = support.HOST |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 43 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 44 | class FakeSocket: |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 45 | def __init__(self, text, fileclass=io.BytesIO, host=None, port=None): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 46 | if isinstance(text, str): |
Guido van Rossum | 39478e8 | 2007-08-27 17:23:59 +0000 | [diff] [blame] | 47 | text = text.encode("ascii") |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 48 | self.text = text |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 49 | self.fileclass = fileclass |
Martin v. Löwis | dd5a860 | 2007-06-30 09:22:09 +0000 | [diff] [blame] | 50 | self.data = b'' |
Antoine Pitrou | 90e4774 | 2013-01-02 22:10:47 +0100 | [diff] [blame] | 51 | self.sendall_calls = 0 |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 52 | self.file_closed = False |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 53 | self.host = host |
| 54 | self.port = port |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 55 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 56 | def sendall(self, data): |
Antoine Pitrou | 90e4774 | 2013-01-02 22:10:47 +0100 | [diff] [blame] | 57 | self.sendall_calls += 1 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 58 | self.data += data |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 59 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 60 | def makefile(self, mode, bufsize=None): |
| 61 | if mode != 'r' and mode != 'rb': |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 62 | raise client.UnimplementedFileMode() |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 63 | # keep the file around so we can check how much was read from it |
| 64 | self.file = self.fileclass(self.text) |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 65 | self.file.close = self.file_close #nerf close () |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 66 | return self.file |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 67 | |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 68 | def file_close(self): |
| 69 | self.file_closed = True |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 70 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 71 | def close(self): |
| 72 | pass |
| 73 | |
Benjamin Peterson | 9d8a3ad | 2015-01-23 11:02:57 -0500 | [diff] [blame] | 74 | def setsockopt(self, level, optname, value): |
| 75 | pass |
| 76 | |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 77 | class EPipeSocket(FakeSocket): |
| 78 | |
| 79 | def __init__(self, text, pipe_trigger): |
| 80 | # When sendall() is called with pipe_trigger, raise EPIPE. |
| 81 | FakeSocket.__init__(self, text) |
| 82 | self.pipe_trigger = pipe_trigger |
| 83 | |
| 84 | def sendall(self, data): |
| 85 | if self.pipe_trigger in data: |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 86 | raise OSError(errno.EPIPE, "gotcha") |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 87 | self.data += data |
| 88 | |
| 89 | def close(self): |
| 90 | pass |
| 91 | |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 92 | class NoEOFBytesIO(io.BytesIO): |
| 93 | """Like BytesIO, but raises AssertionError on EOF. |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 94 | |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 95 | This is used below to test that http.client doesn't try to read |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 96 | more from the underlying file than it should. |
| 97 | """ |
| 98 | def read(self, n=-1): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 99 | data = io.BytesIO.read(self, n) |
Jeremy Hylton | da3f228 | 2007-08-29 17:26:34 +0000 | [diff] [blame] | 100 | if data == b'': |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 101 | raise AssertionError('caller tried to read past EOF') |
| 102 | return data |
| 103 | |
| 104 | def readline(self, length=None): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 105 | data = io.BytesIO.readline(self, length) |
Jeremy Hylton | da3f228 | 2007-08-29 17:26:34 +0000 | [diff] [blame] | 106 | if data == b'': |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 107 | raise AssertionError('caller tried to read past EOF') |
| 108 | return data |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 109 | |
R David Murray | cae7bdb | 2015-04-05 19:26:29 -0400 | [diff] [blame] | 110 | class FakeSocketHTTPConnection(client.HTTPConnection): |
| 111 | """HTTPConnection subclass using FakeSocket; counts connect() calls""" |
| 112 | |
| 113 | def __init__(self, *args): |
| 114 | self.connections = 0 |
| 115 | super().__init__('example.com') |
| 116 | self.fake_socket_args = args |
| 117 | self._create_connection = self.create_connection |
| 118 | |
| 119 | def connect(self): |
| 120 | """Count the number of times connect() is invoked""" |
| 121 | self.connections += 1 |
| 122 | return super().connect() |
| 123 | |
| 124 | def create_connection(self, *pos, **kw): |
| 125 | return FakeSocket(*self.fake_socket_args) |
| 126 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 127 | class HeaderTests(TestCase): |
| 128 | def test_auto_headers(self): |
| 129 | # Some headers are added automatically, but should not be added by |
| 130 | # .request() if they are explicitly set. |
| 131 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 132 | class HeaderCountingBuffer(list): |
| 133 | def __init__(self): |
| 134 | self.count = {} |
| 135 | def append(self, item): |
Guido van Rossum | 022c474 | 2007-08-29 02:00:20 +0000 | [diff] [blame] | 136 | kv = item.split(b':') |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 137 | if len(kv) > 1: |
| 138 | # item is a 'Key: Value' header string |
Martin v. Löwis | dd5a860 | 2007-06-30 09:22:09 +0000 | [diff] [blame] | 139 | lcKey = kv[0].decode('ascii').lower() |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 140 | self.count.setdefault(lcKey, 0) |
| 141 | self.count[lcKey] += 1 |
| 142 | list.append(self, item) |
| 143 | |
| 144 | for explicit_header in True, False: |
| 145 | for header in 'Content-length', 'Host', 'Accept-encoding': |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 146 | conn = client.HTTPConnection('example.com') |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 147 | conn.sock = FakeSocket('blahblahblah') |
| 148 | conn._buffer = HeaderCountingBuffer() |
| 149 | |
| 150 | body = 'spamspamspam' |
| 151 | headers = {} |
| 152 | if explicit_header: |
| 153 | headers[header] = str(len(body)) |
| 154 | conn.request('POST', '/', body, headers) |
| 155 | self.assertEqual(conn._buffer.count[header.lower()], 1) |
| 156 | |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 157 | def test_content_length_0(self): |
| 158 | |
| 159 | class ContentLengthChecker(list): |
| 160 | def __init__(self): |
| 161 | list.__init__(self) |
| 162 | self.content_length = None |
| 163 | def append(self, item): |
| 164 | kv = item.split(b':', 1) |
| 165 | if len(kv) > 1 and kv[0].lower() == b'content-length': |
| 166 | self.content_length = kv[1].strip() |
| 167 | list.append(self, item) |
| 168 | |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 169 | # Here, we're testing that methods expecting a body get a |
| 170 | # content-length set to zero if the body is empty (either None or '') |
| 171 | bodies = (None, '') |
| 172 | methods_with_body = ('PUT', 'POST', 'PATCH') |
| 173 | for method, body in itertools.product(methods_with_body, bodies): |
| 174 | conn = client.HTTPConnection('example.com') |
| 175 | conn.sock = FakeSocket(None) |
| 176 | conn._buffer = ContentLengthChecker() |
| 177 | conn.request(method, '/', body) |
| 178 | self.assertEqual( |
| 179 | conn._buffer.content_length, b'0', |
| 180 | 'Header Content-Length incorrect on {}'.format(method) |
| 181 | ) |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 182 | |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 183 | # For these methods, we make sure that content-length is not set when |
| 184 | # the body is None because it might cause unexpected behaviour on the |
| 185 | # server. |
| 186 | methods_without_body = ( |
| 187 | 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE', |
| 188 | ) |
| 189 | for method in methods_without_body: |
| 190 | conn = client.HTTPConnection('example.com') |
| 191 | conn.sock = FakeSocket(None) |
| 192 | conn._buffer = ContentLengthChecker() |
| 193 | conn.request(method, '/', None) |
| 194 | self.assertEqual( |
| 195 | conn._buffer.content_length, None, |
| 196 | 'Header Content-Length set for empty body on {}'.format(method) |
| 197 | ) |
| 198 | |
| 199 | # If the body is set to '', that's considered to be "present but |
| 200 | # empty" rather than "missing", so content length would be set, even |
| 201 | # for methods that don't expect a body. |
| 202 | for method in methods_without_body: |
| 203 | conn = client.HTTPConnection('example.com') |
| 204 | conn.sock = FakeSocket(None) |
| 205 | conn._buffer = ContentLengthChecker() |
| 206 | conn.request(method, '/', '') |
| 207 | self.assertEqual( |
| 208 | conn._buffer.content_length, b'0', |
| 209 | 'Header Content-Length incorrect on {}'.format(method) |
| 210 | ) |
| 211 | |
| 212 | # If the body is set, make sure Content-Length is set. |
| 213 | for method in itertools.chain(methods_without_body, methods_with_body): |
| 214 | conn = client.HTTPConnection('example.com') |
| 215 | conn.sock = FakeSocket(None) |
| 216 | conn._buffer = ContentLengthChecker() |
| 217 | conn.request(method, '/', ' ') |
| 218 | self.assertEqual( |
| 219 | conn._buffer.content_length, b'1', |
| 220 | 'Header Content-Length incorrect on {}'.format(method) |
| 221 | ) |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 222 | |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 223 | def test_putheader(self): |
| 224 | conn = client.HTTPConnection('example.com') |
| 225 | conn.sock = FakeSocket(None) |
| 226 | conn.putrequest('GET','/') |
| 227 | conn.putheader('Content-length', 42) |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 228 | self.assertIn(b'Content-length: 42', conn._buffer) |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 229 | |
Serhiy Storchaka | a112a8a | 2015-03-12 11:13:36 +0200 | [diff] [blame] | 230 | conn.putheader('Foo', ' bar ') |
| 231 | self.assertIn(b'Foo: bar ', conn._buffer) |
| 232 | conn.putheader('Bar', '\tbaz\t') |
| 233 | self.assertIn(b'Bar: \tbaz\t', conn._buffer) |
| 234 | conn.putheader('Authorization', 'Bearer mytoken') |
| 235 | self.assertIn(b'Authorization: Bearer mytoken', conn._buffer) |
| 236 | conn.putheader('IterHeader', 'IterA', 'IterB') |
| 237 | self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer) |
| 238 | conn.putheader('LatinHeader', b'\xFF') |
| 239 | self.assertIn(b'LatinHeader: \xFF', conn._buffer) |
| 240 | conn.putheader('Utf8Header', b'\xc3\x80') |
| 241 | self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer) |
| 242 | conn.putheader('C1-Control', b'next\x85line') |
| 243 | self.assertIn(b'C1-Control: next\x85line', conn._buffer) |
| 244 | conn.putheader('Embedded-Fold-Space', 'is\r\n allowed') |
| 245 | self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer) |
| 246 | conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed') |
| 247 | self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer) |
| 248 | conn.putheader('Key Space', 'value') |
| 249 | self.assertIn(b'Key Space: value', conn._buffer) |
| 250 | conn.putheader('KeySpace ', 'value') |
| 251 | self.assertIn(b'KeySpace : value', conn._buffer) |
| 252 | conn.putheader(b'Nonbreak\xa0Space', 'value') |
| 253 | self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer) |
| 254 | conn.putheader(b'\xa0NonbreakSpace', 'value') |
| 255 | self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer) |
| 256 | |
Senthil Kumaran | 74ebd9e | 2010-11-13 12:27:49 +0000 | [diff] [blame] | 257 | def test_ipv6host_header(self): |
| 258 | # Default host header on IPv6 transaction should wrapped by [] if |
| 259 | # its actual IPv6 address |
| 260 | expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \ |
| 261 | b'Accept-Encoding: identity\r\n\r\n' |
| 262 | conn = client.HTTPConnection('[2001::]:81') |
| 263 | sock = FakeSocket('') |
| 264 | conn.sock = sock |
| 265 | conn.request('GET', '/foo') |
| 266 | self.assertTrue(sock.data.startswith(expected)) |
| 267 | |
| 268 | expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \ |
| 269 | b'Accept-Encoding: identity\r\n\r\n' |
| 270 | conn = client.HTTPConnection('[2001:102A::]') |
| 271 | sock = FakeSocket('') |
| 272 | conn.sock = sock |
| 273 | conn.request('GET', '/foo') |
| 274 | self.assertTrue(sock.data.startswith(expected)) |
| 275 | |
Benjamin Peterson | 155ceaa | 2015-01-25 23:30:30 -0500 | [diff] [blame] | 276 | def test_malformed_headers_coped_with(self): |
| 277 | # Issue 19996 |
| 278 | body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n" |
| 279 | sock = FakeSocket(body) |
| 280 | resp = client.HTTPResponse(sock) |
| 281 | resp.begin() |
| 282 | |
| 283 | self.assertEqual(resp.getheader('First'), 'val') |
| 284 | self.assertEqual(resp.getheader('Second'), 'val') |
| 285 | |
Serhiy Storchaka | a112a8a | 2015-03-12 11:13:36 +0200 | [diff] [blame] | 286 | def test_invalid_headers(self): |
| 287 | conn = client.HTTPConnection('example.com') |
| 288 | conn.sock = FakeSocket('') |
| 289 | conn.putrequest('GET', '/') |
| 290 | |
| 291 | # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no |
| 292 | # longer allowed in header names |
| 293 | cases = ( |
| 294 | (b'Invalid\r\nName', b'ValidValue'), |
| 295 | (b'Invalid\rName', b'ValidValue'), |
| 296 | (b'Invalid\nName', b'ValidValue'), |
| 297 | (b'\r\nInvalidName', b'ValidValue'), |
| 298 | (b'\rInvalidName', b'ValidValue'), |
| 299 | (b'\nInvalidName', b'ValidValue'), |
| 300 | (b' InvalidName', b'ValidValue'), |
| 301 | (b'\tInvalidName', b'ValidValue'), |
| 302 | (b'Invalid:Name', b'ValidValue'), |
| 303 | (b':InvalidName', b'ValidValue'), |
| 304 | (b'ValidName', b'Invalid\r\nValue'), |
| 305 | (b'ValidName', b'Invalid\rValue'), |
| 306 | (b'ValidName', b'Invalid\nValue'), |
| 307 | (b'ValidName', b'InvalidValue\r\n'), |
| 308 | (b'ValidName', b'InvalidValue\r'), |
| 309 | (b'ValidName', b'InvalidValue\n'), |
| 310 | ) |
| 311 | for name, value in cases: |
| 312 | with self.subTest((name, value)): |
| 313 | with self.assertRaisesRegex(ValueError, 'Invalid header'): |
| 314 | conn.putheader(name, value) |
| 315 | |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 316 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 317 | class BasicTest(TestCase): |
| 318 | def test_status_lines(self): |
| 319 | # Test HTTP status lines |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 320 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 321 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 322 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 323 | resp = client.HTTPResponse(sock) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 324 | resp.begin() |
Serhiy Storchaka | 1c84ac1 | 2013-12-17 21:50:02 +0200 | [diff] [blame] | 325 | self.assertEqual(resp.read(0), b'') # Issue #20007 |
| 326 | self.assertFalse(resp.isclosed()) |
| 327 | self.assertFalse(resp.closed) |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 328 | self.assertEqual(resp.read(), b"Text") |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 329 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 330 | self.assertFalse(resp.closed) |
| 331 | resp.close() |
| 332 | self.assertTrue(resp.closed) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 333 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 334 | body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" |
| 335 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 336 | resp = client.HTTPResponse(sock) |
| 337 | self.assertRaises(client.BadStatusLine, resp.begin) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 338 | |
Benjamin Peterson | 11dbfd4 | 2010-03-21 22:50:04 +0000 | [diff] [blame] | 339 | def test_bad_status_repr(self): |
| 340 | exc = client.BadStatusLine('') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 341 | self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''') |
Benjamin Peterson | 11dbfd4 | 2010-03-21 22:50:04 +0000 | [diff] [blame] | 342 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 343 | def test_partial_reads(self): |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 344 | # if we have a length, the system knows when to close itself |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 345 | # same behaviour than when we read the whole thing with read() |
| 346 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" |
| 347 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 348 | resp = client.HTTPResponse(sock) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 349 | resp.begin() |
| 350 | self.assertEqual(resp.read(2), b'Te') |
| 351 | self.assertFalse(resp.isclosed()) |
| 352 | self.assertEqual(resp.read(2), b'xt') |
| 353 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 354 | self.assertFalse(resp.closed) |
| 355 | resp.close() |
| 356 | self.assertTrue(resp.closed) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 357 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 358 | def test_partial_readintos(self): |
Antoine Pitrou | d20e774 | 2012-12-15 19:22:30 +0100 | [diff] [blame] | 359 | # if we have a length, the system knows when to close itself |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 360 | # same behaviour than when we read the whole thing with read() |
| 361 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" |
| 362 | sock = FakeSocket(body) |
| 363 | resp = client.HTTPResponse(sock) |
| 364 | resp.begin() |
| 365 | b = bytearray(2) |
| 366 | n = resp.readinto(b) |
| 367 | self.assertEqual(n, 2) |
| 368 | self.assertEqual(bytes(b), b'Te') |
| 369 | self.assertFalse(resp.isclosed()) |
| 370 | n = resp.readinto(b) |
| 371 | self.assertEqual(n, 2) |
| 372 | self.assertEqual(bytes(b), b'xt') |
| 373 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b6c86fd | 2013-02-06 10:35:40 +0200 | [diff] [blame] | 374 | self.assertFalse(resp.closed) |
| 375 | resp.close() |
| 376 | self.assertTrue(resp.closed) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 377 | |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 378 | def test_partial_reads_no_content_length(self): |
| 379 | # when no length is present, the socket should be gracefully closed when |
| 380 | # all data was read |
| 381 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 382 | sock = FakeSocket(body) |
| 383 | resp = client.HTTPResponse(sock) |
| 384 | resp.begin() |
| 385 | self.assertEqual(resp.read(2), b'Te') |
| 386 | self.assertFalse(resp.isclosed()) |
| 387 | self.assertEqual(resp.read(2), b'xt') |
| 388 | self.assertEqual(resp.read(1), b'') |
| 389 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 390 | self.assertFalse(resp.closed) |
| 391 | resp.close() |
| 392 | self.assertTrue(resp.closed) |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 393 | |
Antoine Pitrou | d20e774 | 2012-12-15 19:22:30 +0100 | [diff] [blame] | 394 | def test_partial_readintos_no_content_length(self): |
| 395 | # when no length is present, the socket should be gracefully closed when |
| 396 | # all data was read |
| 397 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 398 | sock = FakeSocket(body) |
| 399 | resp = client.HTTPResponse(sock) |
| 400 | resp.begin() |
| 401 | b = bytearray(2) |
| 402 | n = resp.readinto(b) |
| 403 | self.assertEqual(n, 2) |
| 404 | self.assertEqual(bytes(b), b'Te') |
| 405 | self.assertFalse(resp.isclosed()) |
| 406 | n = resp.readinto(b) |
| 407 | self.assertEqual(n, 2) |
| 408 | self.assertEqual(bytes(b), b'xt') |
| 409 | n = resp.readinto(b) |
| 410 | self.assertEqual(n, 0) |
| 411 | self.assertTrue(resp.isclosed()) |
| 412 | |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 413 | def test_partial_reads_incomplete_body(self): |
| 414 | # if the server shuts down the connection before the whole |
| 415 | # content-length is delivered, the socket is gracefully closed |
| 416 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" |
| 417 | sock = FakeSocket(body) |
| 418 | resp = client.HTTPResponse(sock) |
| 419 | resp.begin() |
| 420 | self.assertEqual(resp.read(2), b'Te') |
| 421 | self.assertFalse(resp.isclosed()) |
| 422 | self.assertEqual(resp.read(2), b'xt') |
| 423 | self.assertEqual(resp.read(1), b'') |
| 424 | self.assertTrue(resp.isclosed()) |
| 425 | |
Antoine Pitrou | 6a35e18 | 2013-02-02 23:04:56 +0100 | [diff] [blame] | 426 | def test_partial_readintos_incomplete_body(self): |
| 427 | # if the server shuts down the connection before the whole |
| 428 | # content-length is delivered, the socket is gracefully closed |
| 429 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" |
| 430 | sock = FakeSocket(body) |
| 431 | resp = client.HTTPResponse(sock) |
| 432 | resp.begin() |
| 433 | b = bytearray(2) |
| 434 | n = resp.readinto(b) |
| 435 | self.assertEqual(n, 2) |
| 436 | self.assertEqual(bytes(b), b'Te') |
| 437 | self.assertFalse(resp.isclosed()) |
| 438 | n = resp.readinto(b) |
| 439 | self.assertEqual(n, 2) |
| 440 | self.assertEqual(bytes(b), b'xt') |
| 441 | n = resp.readinto(b) |
| 442 | self.assertEqual(n, 0) |
| 443 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 444 | self.assertFalse(resp.closed) |
| 445 | resp.close() |
| 446 | self.assertTrue(resp.closed) |
Antoine Pitrou | 6a35e18 | 2013-02-02 23:04:56 +0100 | [diff] [blame] | 447 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 448 | def test_host_port(self): |
| 449 | # Check invalid host_port |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 450 | |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 451 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 452 | self.assertRaises(client.InvalidURL, client.HTTPConnection, hp) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 453 | |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 454 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", |
| 455 | "fe80::207:e9ff:fe9b", 8000), |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 456 | ("www.python.org:80", "www.python.org", 80), |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 457 | ("www.python.org:", "www.python.org", 80), |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 458 | ("www.python.org", "www.python.org", 80), |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 459 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80), |
| 460 | ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 461 | c = client.HTTPConnection(hp) |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 462 | self.assertEqual(h, c.host) |
| 463 | self.assertEqual(p, c.port) |
Skip Montanaro | 10e6e0e | 2004-09-14 16:32:02 +0000 | [diff] [blame] | 464 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 465 | def test_response_headers(self): |
| 466 | # test response with multiple message headers with the same field name. |
| 467 | text = ('HTTP/1.1 200 OK\r\n' |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 468 | 'Set-Cookie: Customer="WILE_E_COYOTE"; ' |
| 469 | 'Version="1"; Path="/acme"\r\n' |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 470 | 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' |
| 471 | ' Path="/acme"\r\n' |
| 472 | '\r\n' |
| 473 | 'No body\r\n') |
| 474 | hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' |
| 475 | ', ' |
| 476 | 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') |
| 477 | s = FakeSocket(text) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 478 | r = client.HTTPResponse(s) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 479 | r.begin() |
| 480 | cookies = r.getheader("Set-Cookie") |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 481 | self.assertEqual(cookies, hdr) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 482 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 483 | def test_read_head(self): |
| 484 | # Test that the library doesn't attempt to read any data |
| 485 | # from a HEAD request. (Tickles SF bug #622042.) |
| 486 | sock = FakeSocket( |
| 487 | 'HTTP/1.1 200 OK\r\n' |
| 488 | 'Content-Length: 14432\r\n' |
| 489 | '\r\n', |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 490 | NoEOFBytesIO) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 491 | resp = client.HTTPResponse(sock, method="HEAD") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 492 | resp.begin() |
Guido van Rossum | a00f123 | 2007-09-12 19:43:09 +0000 | [diff] [blame] | 493 | if resp.read(): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 494 | self.fail("Did not expect response from HEAD request") |
Jeremy Hylton | c1b2cb9 | 2003-05-05 16:13:58 +0000 | [diff] [blame] | 495 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 496 | def test_readinto_head(self): |
| 497 | # Test that the library doesn't attempt to read any data |
| 498 | # from a HEAD request. (Tickles SF bug #622042.) |
| 499 | sock = FakeSocket( |
| 500 | 'HTTP/1.1 200 OK\r\n' |
| 501 | 'Content-Length: 14432\r\n' |
| 502 | '\r\n', |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 503 | NoEOFBytesIO) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 504 | resp = client.HTTPResponse(sock, method="HEAD") |
| 505 | resp.begin() |
| 506 | b = bytearray(5) |
| 507 | if resp.readinto(b) != 0: |
| 508 | self.fail("Did not expect response from HEAD request") |
| 509 | self.assertEqual(bytes(b), b'\x00'*5) |
| 510 | |
Georg Brandl | bf3f8eb | 2013-10-27 07:34:48 +0100 | [diff] [blame] | 511 | def test_too_many_headers(self): |
| 512 | headers = '\r\n'.join('Header%d: foo' % i |
| 513 | for i in range(client._MAXHEADERS + 1)) + '\r\n' |
| 514 | text = ('HTTP/1.1 200 OK\r\n' + headers) |
| 515 | s = FakeSocket(text) |
| 516 | r = client.HTTPResponse(s) |
| 517 | self.assertRaisesRegex(client.HTTPException, |
| 518 | r"got more than \d+ headers", r.begin) |
| 519 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 520 | def test_send_file(self): |
Guido van Rossum | 022c474 | 2007-08-29 02:00:20 +0000 | [diff] [blame] | 521 | expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' |
| 522 | b'Accept-Encoding: identity\r\nContent-Length:') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 523 | |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 524 | with open(__file__, 'rb') as body: |
| 525 | conn = client.HTTPConnection('example.com') |
| 526 | sock = FakeSocket(body) |
| 527 | conn.sock = sock |
| 528 | conn.request('GET', '/foo', body) |
| 529 | self.assertTrue(sock.data.startswith(expected), '%r != %r' % |
| 530 | (sock.data[:len(expected)], expected)) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 531 | |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 532 | def test_send(self): |
| 533 | expected = b'this is a test this is only a test' |
| 534 | conn = client.HTTPConnection('example.com') |
| 535 | sock = FakeSocket(None) |
| 536 | conn.sock = sock |
| 537 | conn.send(expected) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 538 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 539 | sock.data = b'' |
| 540 | conn.send(array.array('b', expected)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 541 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 542 | sock.data = b'' |
| 543 | conn.send(io.BytesIO(expected)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 544 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 545 | |
Andrew Svetlov | 7b2c8bb | 2013-04-12 22:49:19 +0300 | [diff] [blame] | 546 | def test_send_updating_file(self): |
| 547 | def data(): |
| 548 | yield 'data' |
| 549 | yield None |
| 550 | yield 'data_two' |
| 551 | |
| 552 | class UpdatingFile(): |
| 553 | mode = 'r' |
| 554 | d = data() |
| 555 | def read(self, blocksize=-1): |
| 556 | return self.d.__next__() |
| 557 | |
| 558 | expected = b'data' |
| 559 | |
| 560 | conn = client.HTTPConnection('example.com') |
| 561 | sock = FakeSocket("") |
| 562 | conn.sock = sock |
| 563 | conn.send(UpdatingFile()) |
| 564 | self.assertEqual(sock.data, expected) |
| 565 | |
| 566 | |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 567 | def test_send_iter(self): |
| 568 | expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ |
| 569 | b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \ |
| 570 | b'\r\nonetwothree' |
| 571 | |
| 572 | def body(): |
| 573 | yield b"one" |
| 574 | yield b"two" |
| 575 | yield b"three" |
| 576 | |
| 577 | conn = client.HTTPConnection('example.com') |
| 578 | sock = FakeSocket("") |
| 579 | conn.sock = sock |
| 580 | conn.request('GET', '/foo', body(), {'Content-Length': '11'}) |
Victor Stinner | 04ba966 | 2011-01-04 00:04:46 +0000 | [diff] [blame] | 581 | self.assertEqual(sock.data, expected) |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 582 | |
Senthil Kumaran | eb71ad4 | 2011-08-02 18:33:41 +0800 | [diff] [blame] | 583 | def test_send_type_error(self): |
| 584 | # See: Issue #12676 |
| 585 | conn = client.HTTPConnection('example.com') |
| 586 | conn.sock = FakeSocket('') |
| 587 | with self.assertRaises(TypeError): |
| 588 | conn.request('POST', 'test', conn) |
| 589 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 590 | def test_chunked(self): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 591 | expected = chunked_expected |
| 592 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 593 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 594 | resp.begin() |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 595 | self.assertEqual(resp.read(), expected) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 596 | resp.close() |
| 597 | |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 598 | # Various read sizes |
| 599 | for n in range(1, 12): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 600 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 601 | resp = client.HTTPResponse(sock, method="GET") |
| 602 | resp.begin() |
| 603 | self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected) |
| 604 | resp.close() |
| 605 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 606 | for x in ('', 'foo\r\n'): |
| 607 | sock = FakeSocket(chunked_start + x) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 608 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 609 | resp.begin() |
| 610 | try: |
| 611 | resp.read() |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 612 | except client.IncompleteRead as i: |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 613 | self.assertEqual(i.partial, expected) |
| 614 | expected_message = 'IncompleteRead(%d bytes read)' % len(expected) |
| 615 | self.assertEqual(repr(i), expected_message) |
| 616 | self.assertEqual(str(i), expected_message) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 617 | else: |
| 618 | self.fail('IncompleteRead expected') |
| 619 | finally: |
| 620 | resp.close() |
| 621 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 622 | def test_readinto_chunked(self): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 623 | |
| 624 | expected = chunked_expected |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 625 | nexpected = len(expected) |
| 626 | b = bytearray(128) |
| 627 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 628 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 629 | resp = client.HTTPResponse(sock, method="GET") |
| 630 | resp.begin() |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 631 | n = resp.readinto(b) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 632 | self.assertEqual(b[:nexpected], expected) |
| 633 | self.assertEqual(n, nexpected) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 634 | resp.close() |
| 635 | |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 636 | # Various read sizes |
| 637 | for n in range(1, 12): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 638 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 639 | resp = client.HTTPResponse(sock, method="GET") |
| 640 | resp.begin() |
| 641 | m = memoryview(b) |
| 642 | i = resp.readinto(m[0:n]) |
| 643 | i += resp.readinto(m[i:n + i]) |
| 644 | i += resp.readinto(m[i:]) |
| 645 | self.assertEqual(b[:nexpected], expected) |
| 646 | self.assertEqual(i, nexpected) |
| 647 | resp.close() |
| 648 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 649 | for x in ('', 'foo\r\n'): |
| 650 | sock = FakeSocket(chunked_start + x) |
| 651 | resp = client.HTTPResponse(sock, method="GET") |
| 652 | resp.begin() |
| 653 | try: |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 654 | n = resp.readinto(b) |
| 655 | except client.IncompleteRead as i: |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 656 | self.assertEqual(i.partial, expected) |
| 657 | expected_message = 'IncompleteRead(%d bytes read)' % len(expected) |
| 658 | self.assertEqual(repr(i), expected_message) |
| 659 | self.assertEqual(str(i), expected_message) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 660 | else: |
| 661 | self.fail('IncompleteRead expected') |
| 662 | finally: |
| 663 | resp.close() |
| 664 | |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 665 | def test_chunked_head(self): |
| 666 | chunked_start = ( |
| 667 | 'HTTP/1.1 200 OK\r\n' |
| 668 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 669 | 'a\r\n' |
| 670 | 'hello world\r\n' |
| 671 | '1\r\n' |
| 672 | 'd\r\n' |
| 673 | ) |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 674 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 675 | resp = client.HTTPResponse(sock, method="HEAD") |
| 676 | resp.begin() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 677 | self.assertEqual(resp.read(), b'') |
| 678 | self.assertEqual(resp.status, 200) |
| 679 | self.assertEqual(resp.reason, 'OK') |
Senthil Kumaran | 0b99883 | 2010-06-04 17:27:11 +0000 | [diff] [blame] | 680 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 681 | self.assertFalse(resp.closed) |
| 682 | resp.close() |
| 683 | self.assertTrue(resp.closed) |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 684 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 685 | def test_readinto_chunked_head(self): |
| 686 | chunked_start = ( |
| 687 | 'HTTP/1.1 200 OK\r\n' |
| 688 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 689 | 'a\r\n' |
| 690 | 'hello world\r\n' |
| 691 | '1\r\n' |
| 692 | 'd\r\n' |
| 693 | ) |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 694 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 695 | resp = client.HTTPResponse(sock, method="HEAD") |
| 696 | resp.begin() |
| 697 | b = bytearray(5) |
| 698 | n = resp.readinto(b) |
| 699 | self.assertEqual(n, 0) |
| 700 | self.assertEqual(bytes(b), b'\x00'*5) |
| 701 | self.assertEqual(resp.status, 200) |
| 702 | self.assertEqual(resp.reason, 'OK') |
| 703 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b6c86fd | 2013-02-06 10:35:40 +0200 | [diff] [blame] | 704 | self.assertFalse(resp.closed) |
| 705 | resp.close() |
| 706 | self.assertTrue(resp.closed) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 707 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 708 | def test_negative_content_length(self): |
Jeremy Hylton | 8206695 | 2008-12-15 03:08:30 +0000 | [diff] [blame] | 709 | sock = FakeSocket( |
| 710 | 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 711 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 712 | resp.begin() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 713 | self.assertEqual(resp.read(), b'Hello\r\n') |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 714 | self.assertTrue(resp.isclosed()) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 715 | |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 716 | def test_incomplete_read(self): |
| 717 | sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n') |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 718 | resp = client.HTTPResponse(sock, method="GET") |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 719 | resp.begin() |
| 720 | try: |
| 721 | resp.read() |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 722 | except client.IncompleteRead as i: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 723 | self.assertEqual(i.partial, b'Hello\r\n') |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 724 | self.assertEqual(repr(i), |
| 725 | "IncompleteRead(7 bytes read, 3 more expected)") |
| 726 | self.assertEqual(str(i), |
| 727 | "IncompleteRead(7 bytes read, 3 more expected)") |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 728 | self.assertTrue(resp.isclosed()) |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 729 | else: |
| 730 | self.fail('IncompleteRead expected') |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 731 | |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 732 | def test_epipe(self): |
| 733 | sock = EPipeSocket( |
| 734 | "HTTP/1.0 401 Authorization Required\r\n" |
| 735 | "Content-type: text/html\r\n" |
| 736 | "WWW-Authenticate: Basic realm=\"example\"\r\n", |
| 737 | b"Content-Length") |
| 738 | conn = client.HTTPConnection("example.com") |
| 739 | conn.sock = sock |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 740 | self.assertRaises(OSError, |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 741 | lambda: conn.request("PUT", "/url", "body")) |
| 742 | resp = conn.getresponse() |
| 743 | self.assertEqual(401, resp.status) |
| 744 | self.assertEqual("Basic realm=\"example\"", |
| 745 | resp.getheader("www-authenticate")) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 746 | |
Senthil Kumaran | 5466bf1 | 2010-12-18 16:55:23 +0000 | [diff] [blame] | 747 | # Test lines overflowing the max line size (_MAXLINE in http.client) |
| 748 | |
| 749 | def test_overflowing_status_line(self): |
| 750 | body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n" |
| 751 | resp = client.HTTPResponse(FakeSocket(body)) |
| 752 | self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin) |
| 753 | |
| 754 | def test_overflowing_header_line(self): |
| 755 | body = ( |
| 756 | 'HTTP/1.1 200 OK\r\n' |
| 757 | 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n' |
| 758 | ) |
| 759 | resp = client.HTTPResponse(FakeSocket(body)) |
| 760 | self.assertRaises(client.LineTooLong, resp.begin) |
| 761 | |
| 762 | def test_overflowing_chunked_line(self): |
| 763 | body = ( |
| 764 | 'HTTP/1.1 200 OK\r\n' |
| 765 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 766 | + '0' * 65536 + 'a\r\n' |
| 767 | 'hello world\r\n' |
| 768 | '0\r\n' |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 769 | '\r\n' |
Senthil Kumaran | 5466bf1 | 2010-12-18 16:55:23 +0000 | [diff] [blame] | 770 | ) |
| 771 | resp = client.HTTPResponse(FakeSocket(body)) |
| 772 | resp.begin() |
| 773 | self.assertRaises(client.LineTooLong, resp.read) |
| 774 | |
Senthil Kumaran | 9c29f86 | 2012-04-29 10:20:46 +0800 | [diff] [blame] | 775 | def test_early_eof(self): |
| 776 | # Test httpresponse with no \r\n termination, |
| 777 | body = "HTTP/1.1 200 Ok" |
| 778 | sock = FakeSocket(body) |
| 779 | resp = client.HTTPResponse(sock) |
| 780 | resp.begin() |
| 781 | self.assertEqual(resp.read(), b'') |
| 782 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 783 | self.assertFalse(resp.closed) |
| 784 | resp.close() |
| 785 | self.assertTrue(resp.closed) |
Senthil Kumaran | 9c29f86 | 2012-04-29 10:20:46 +0800 | [diff] [blame] | 786 | |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 787 | def test_error_leak(self): |
| 788 | # Test that the socket is not leaked if getresponse() fails |
| 789 | conn = client.HTTPConnection('example.com') |
| 790 | response = None |
| 791 | class Response(client.HTTPResponse): |
| 792 | def __init__(self, *pos, **kw): |
| 793 | nonlocal response |
| 794 | response = self # Avoid garbage collector closing the socket |
| 795 | client.HTTPResponse.__init__(self, *pos, **kw) |
| 796 | conn.response_class = Response |
R David Murray | cae7bdb | 2015-04-05 19:26:29 -0400 | [diff] [blame] | 797 | conn.sock = FakeSocket('Invalid status line') |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 798 | conn.request('GET', '/') |
| 799 | self.assertRaises(client.BadStatusLine, conn.getresponse) |
| 800 | self.assertTrue(response.closed) |
| 801 | self.assertTrue(conn.sock.file_closed) |
| 802 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 803 | def test_chunked_extension(self): |
| 804 | extra = '3;foo=bar\r\n' + 'abc\r\n' |
| 805 | expected = chunked_expected + b'abc' |
| 806 | |
| 807 | sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end) |
| 808 | resp = client.HTTPResponse(sock, method="GET") |
| 809 | resp.begin() |
| 810 | self.assertEqual(resp.read(), expected) |
| 811 | resp.close() |
| 812 | |
| 813 | def test_chunked_missing_end(self): |
| 814 | """some servers may serve up a short chunked encoding stream""" |
| 815 | expected = chunked_expected |
| 816 | sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf |
| 817 | resp = client.HTTPResponse(sock, method="GET") |
| 818 | resp.begin() |
| 819 | self.assertEqual(resp.read(), expected) |
| 820 | resp.close() |
| 821 | |
| 822 | def test_chunked_trailers(self): |
| 823 | """See that trailers are read and ignored""" |
| 824 | expected = chunked_expected |
| 825 | sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end) |
| 826 | resp = client.HTTPResponse(sock, method="GET") |
| 827 | resp.begin() |
| 828 | self.assertEqual(resp.read(), expected) |
| 829 | # we should have reached the end of the file |
| 830 | self.assertEqual(sock.file.read(100), b"") #we read to the end |
| 831 | resp.close() |
| 832 | |
| 833 | def test_chunked_sync(self): |
| 834 | """Check that we don't read past the end of the chunked-encoding stream""" |
| 835 | expected = chunked_expected |
| 836 | extradata = "extradata" |
| 837 | sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata) |
| 838 | resp = client.HTTPResponse(sock, method="GET") |
| 839 | resp.begin() |
| 840 | self.assertEqual(resp.read(), expected) |
| 841 | # the file should now have our extradata ready to be read |
| 842 | self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end |
| 843 | resp.close() |
| 844 | |
| 845 | def test_content_length_sync(self): |
| 846 | """Check that we don't read past the end of the Content-Length stream""" |
| 847 | extradata = "extradata" |
| 848 | expected = b"Hello123\r\n" |
| 849 | sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello123\r\n' + extradata) |
| 850 | resp = client.HTTPResponse(sock, method="GET") |
| 851 | resp.begin() |
| 852 | self.assertEqual(resp.read(), expected) |
| 853 | # the file should now have our extradata ready to be read |
| 854 | self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end |
| 855 | resp.close() |
| 856 | |
| 857 | class ExtendedReadTest(TestCase): |
| 858 | """ |
| 859 | Test peek(), read1(), readline() |
| 860 | """ |
| 861 | lines = ( |
| 862 | 'HTTP/1.1 200 OK\r\n' |
| 863 | '\r\n' |
| 864 | 'hello world!\n' |
| 865 | 'and now \n' |
| 866 | 'for something completely different\n' |
| 867 | 'foo' |
| 868 | ) |
| 869 | lines_expected = lines[lines.find('hello'):].encode("ascii") |
| 870 | lines_chunked = ( |
| 871 | 'HTTP/1.1 200 OK\r\n' |
| 872 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 873 | 'a\r\n' |
| 874 | 'hello worl\r\n' |
| 875 | '3\r\n' |
| 876 | 'd!\n\r\n' |
| 877 | '9\r\n' |
| 878 | 'and now \n\r\n' |
| 879 | '23\r\n' |
| 880 | 'for something completely different\n\r\n' |
| 881 | '3\r\n' |
| 882 | 'foo\r\n' |
| 883 | '0\r\n' # terminating chunk |
| 884 | '\r\n' # end of trailers |
| 885 | ) |
| 886 | |
| 887 | def setUp(self): |
| 888 | sock = FakeSocket(self.lines) |
| 889 | resp = client.HTTPResponse(sock, method="GET") |
| 890 | resp.begin() |
| 891 | resp.fp = io.BufferedReader(resp.fp) |
| 892 | self.resp = resp |
| 893 | |
| 894 | |
| 895 | |
| 896 | def test_peek(self): |
| 897 | resp = self.resp |
| 898 | # patch up the buffered peek so that it returns not too much stuff |
| 899 | oldpeek = resp.fp.peek |
| 900 | def mypeek(n=-1): |
| 901 | p = oldpeek(n) |
| 902 | if n >= 0: |
| 903 | return p[:n] |
| 904 | return p[:10] |
| 905 | resp.fp.peek = mypeek |
| 906 | |
| 907 | all = [] |
| 908 | while True: |
| 909 | # try a short peek |
| 910 | p = resp.peek(3) |
| 911 | if p: |
| 912 | self.assertGreater(len(p), 0) |
| 913 | # then unbounded peek |
| 914 | p2 = resp.peek() |
| 915 | self.assertGreaterEqual(len(p2), len(p)) |
| 916 | self.assertTrue(p2.startswith(p)) |
| 917 | next = resp.read(len(p2)) |
| 918 | self.assertEqual(next, p2) |
| 919 | else: |
| 920 | next = resp.read() |
| 921 | self.assertFalse(next) |
| 922 | all.append(next) |
| 923 | if not next: |
| 924 | break |
| 925 | self.assertEqual(b"".join(all), self.lines_expected) |
| 926 | |
| 927 | def test_readline(self): |
| 928 | resp = self.resp |
| 929 | self._verify_readline(self.resp.readline, self.lines_expected) |
| 930 | |
| 931 | def _verify_readline(self, readline, expected): |
| 932 | all = [] |
| 933 | while True: |
| 934 | # short readlines |
| 935 | line = readline(5) |
| 936 | if line and line != b"foo": |
| 937 | if len(line) < 5: |
| 938 | self.assertTrue(line.endswith(b"\n")) |
| 939 | all.append(line) |
| 940 | if not line: |
| 941 | break |
| 942 | self.assertEqual(b"".join(all), expected) |
| 943 | |
| 944 | def test_read1(self): |
| 945 | resp = self.resp |
| 946 | def r(): |
| 947 | res = resp.read1(4) |
| 948 | self.assertLessEqual(len(res), 4) |
| 949 | return res |
| 950 | readliner = Readliner(r) |
| 951 | self._verify_readline(readliner.readline, self.lines_expected) |
| 952 | |
| 953 | def test_read1_unbounded(self): |
| 954 | resp = self.resp |
| 955 | all = [] |
| 956 | while True: |
| 957 | data = resp.read1() |
| 958 | if not data: |
| 959 | break |
| 960 | all.append(data) |
| 961 | self.assertEqual(b"".join(all), self.lines_expected) |
| 962 | |
| 963 | def test_read1_bounded(self): |
| 964 | resp = self.resp |
| 965 | all = [] |
| 966 | while True: |
| 967 | data = resp.read1(10) |
| 968 | if not data: |
| 969 | break |
| 970 | self.assertLessEqual(len(data), 10) |
| 971 | all.append(data) |
| 972 | self.assertEqual(b"".join(all), self.lines_expected) |
| 973 | |
| 974 | def test_read1_0(self): |
| 975 | self.assertEqual(self.resp.read1(0), b"") |
| 976 | |
| 977 | def test_peek_0(self): |
| 978 | p = self.resp.peek(0) |
| 979 | self.assertLessEqual(0, len(p)) |
| 980 | |
| 981 | class ExtendedReadTestChunked(ExtendedReadTest): |
| 982 | """ |
| 983 | Test peek(), read1(), readline() in chunked mode |
| 984 | """ |
| 985 | lines = ( |
| 986 | 'HTTP/1.1 200 OK\r\n' |
| 987 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 988 | 'a\r\n' |
| 989 | 'hello worl\r\n' |
| 990 | '3\r\n' |
| 991 | 'd!\n\r\n' |
| 992 | '9\r\n' |
| 993 | 'and now \n\r\n' |
| 994 | '23\r\n' |
| 995 | 'for something completely different\n\r\n' |
| 996 | '3\r\n' |
| 997 | 'foo\r\n' |
| 998 | '0\r\n' # terminating chunk |
| 999 | '\r\n' # end of trailers |
| 1000 | ) |
| 1001 | |
| 1002 | |
| 1003 | class Readliner: |
| 1004 | """ |
| 1005 | a simple readline class that uses an arbitrary read function and buffering |
| 1006 | """ |
| 1007 | def __init__(self, readfunc): |
| 1008 | self.readfunc = readfunc |
| 1009 | self.remainder = b"" |
| 1010 | |
| 1011 | def readline(self, limit): |
| 1012 | data = [] |
| 1013 | datalen = 0 |
| 1014 | read = self.remainder |
| 1015 | try: |
| 1016 | while True: |
| 1017 | idx = read.find(b'\n') |
| 1018 | if idx != -1: |
| 1019 | break |
| 1020 | if datalen + len(read) >= limit: |
| 1021 | idx = limit - datalen - 1 |
| 1022 | # read more data |
| 1023 | data.append(read) |
| 1024 | read = self.readfunc() |
| 1025 | if not read: |
| 1026 | idx = 0 #eof condition |
| 1027 | break |
| 1028 | idx += 1 |
| 1029 | data.append(read[:idx]) |
| 1030 | self.remainder = read[idx:] |
| 1031 | return b"".join(data) |
| 1032 | except: |
| 1033 | self.remainder = b"".join(data) |
| 1034 | raise |
| 1035 | |
Berker Peksag | babc688 | 2015-02-20 09:39:38 +0200 | [diff] [blame] | 1036 | |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1037 | class OfflineTest(TestCase): |
Berker Peksag | babc688 | 2015-02-20 09:39:38 +0200 | [diff] [blame] | 1038 | def test_all(self): |
| 1039 | # Documented objects defined in the module should be in __all__ |
| 1040 | expected = {"responses"} # White-list documented dict() object |
| 1041 | # HTTPMessage, parse_headers(), and the HTTP status code constants are |
| 1042 | # intentionally omitted for simplicity |
| 1043 | blacklist = {"HTTPMessage", "parse_headers"} |
| 1044 | for name in dir(client): |
| 1045 | if name in blacklist: |
| 1046 | continue |
| 1047 | module_object = getattr(client, name) |
| 1048 | if getattr(module_object, "__module__", None) == "http.client": |
| 1049 | expected.add(name) |
| 1050 | self.assertCountEqual(client.__all__, expected) |
| 1051 | |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1052 | def test_responses(self): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1053 | self.assertEqual(client.responses[client.NOT_FOUND], "Not Found") |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1054 | |
Berker Peksag | abbf0f4 | 2015-02-20 14:57:31 +0200 | [diff] [blame] | 1055 | def test_client_constants(self): |
| 1056 | # Make sure we don't break backward compatibility with 3.4 |
| 1057 | expected = [ |
| 1058 | 'CONTINUE', |
| 1059 | 'SWITCHING_PROTOCOLS', |
| 1060 | 'PROCESSING', |
| 1061 | 'OK', |
| 1062 | 'CREATED', |
| 1063 | 'ACCEPTED', |
| 1064 | 'NON_AUTHORITATIVE_INFORMATION', |
| 1065 | 'NO_CONTENT', |
| 1066 | 'RESET_CONTENT', |
| 1067 | 'PARTIAL_CONTENT', |
| 1068 | 'MULTI_STATUS', |
| 1069 | 'IM_USED', |
| 1070 | 'MULTIPLE_CHOICES', |
| 1071 | 'MOVED_PERMANENTLY', |
| 1072 | 'FOUND', |
| 1073 | 'SEE_OTHER', |
| 1074 | 'NOT_MODIFIED', |
| 1075 | 'USE_PROXY', |
| 1076 | 'TEMPORARY_REDIRECT', |
| 1077 | 'BAD_REQUEST', |
| 1078 | 'UNAUTHORIZED', |
| 1079 | 'PAYMENT_REQUIRED', |
| 1080 | 'FORBIDDEN', |
| 1081 | 'NOT_FOUND', |
| 1082 | 'METHOD_NOT_ALLOWED', |
| 1083 | 'NOT_ACCEPTABLE', |
| 1084 | 'PROXY_AUTHENTICATION_REQUIRED', |
| 1085 | 'REQUEST_TIMEOUT', |
| 1086 | 'CONFLICT', |
| 1087 | 'GONE', |
| 1088 | 'LENGTH_REQUIRED', |
| 1089 | 'PRECONDITION_FAILED', |
| 1090 | 'REQUEST_ENTITY_TOO_LARGE', |
| 1091 | 'REQUEST_URI_TOO_LONG', |
| 1092 | 'UNSUPPORTED_MEDIA_TYPE', |
| 1093 | 'REQUESTED_RANGE_NOT_SATISFIABLE', |
| 1094 | 'EXPECTATION_FAILED', |
| 1095 | 'UNPROCESSABLE_ENTITY', |
| 1096 | 'LOCKED', |
| 1097 | 'FAILED_DEPENDENCY', |
| 1098 | 'UPGRADE_REQUIRED', |
| 1099 | 'PRECONDITION_REQUIRED', |
| 1100 | 'TOO_MANY_REQUESTS', |
| 1101 | 'REQUEST_HEADER_FIELDS_TOO_LARGE', |
| 1102 | 'INTERNAL_SERVER_ERROR', |
| 1103 | 'NOT_IMPLEMENTED', |
| 1104 | 'BAD_GATEWAY', |
| 1105 | 'SERVICE_UNAVAILABLE', |
| 1106 | 'GATEWAY_TIMEOUT', |
| 1107 | 'HTTP_VERSION_NOT_SUPPORTED', |
| 1108 | 'INSUFFICIENT_STORAGE', |
| 1109 | 'NOT_EXTENDED', |
| 1110 | 'NETWORK_AUTHENTICATION_REQUIRED', |
| 1111 | ] |
| 1112 | for const in expected: |
| 1113 | with self.subTest(constant=const): |
| 1114 | self.assertTrue(hasattr(client, const)) |
| 1115 | |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 1116 | |
| 1117 | class SourceAddressTest(TestCase): |
| 1118 | def setUp(self): |
| 1119 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1120 | self.port = support.bind_port(self.serv) |
| 1121 | self.source_port = support.find_unused_port() |
Charles-François Natali | 6e20460 | 2014-07-23 19:28:13 +0100 | [diff] [blame] | 1122 | self.serv.listen() |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 1123 | self.conn = None |
| 1124 | |
| 1125 | def tearDown(self): |
| 1126 | if self.conn: |
| 1127 | self.conn.close() |
| 1128 | self.conn = None |
| 1129 | self.serv.close() |
| 1130 | self.serv = None |
| 1131 | |
| 1132 | def testHTTPConnectionSourceAddress(self): |
| 1133 | self.conn = client.HTTPConnection(HOST, self.port, |
| 1134 | source_address=('', self.source_port)) |
| 1135 | self.conn.connect() |
| 1136 | self.assertEqual(self.conn.sock.getsockname()[1], self.source_port) |
| 1137 | |
| 1138 | @unittest.skipIf(not hasattr(client, 'HTTPSConnection'), |
| 1139 | 'http.client.HTTPSConnection not defined') |
| 1140 | def testHTTPSConnectionSourceAddress(self): |
| 1141 | self.conn = client.HTTPSConnection(HOST, self.port, |
| 1142 | source_address=('', self.source_port)) |
| 1143 | # We don't test anything here other the constructor not barfing as |
| 1144 | # this code doesn't deal with setting up an active running SSL server |
| 1145 | # for an ssl_wrapped connect() to actually return from. |
| 1146 | |
| 1147 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1148 | class TimeoutTest(TestCase): |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 1149 | PORT = None |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1150 | |
| 1151 | def setUp(self): |
| 1152 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1153 | TimeoutTest.PORT = support.bind_port(self.serv) |
Charles-François Natali | 6e20460 | 2014-07-23 19:28:13 +0100 | [diff] [blame] | 1154 | self.serv.listen() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1155 | |
| 1156 | def tearDown(self): |
| 1157 | self.serv.close() |
| 1158 | self.serv = None |
| 1159 | |
| 1160 | def testTimeoutAttribute(self): |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 1161 | # This will prove that the timeout gets through HTTPConnection |
| 1162 | # and into the socket. |
| 1163 | |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1164 | # default -- use global socket timeout |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 1165 | self.assertIsNone(socket.getdefaulttimeout()) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1166 | socket.setdefaulttimeout(30) |
| 1167 | try: |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1168 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1169 | httpConn.connect() |
| 1170 | finally: |
| 1171 | socket.setdefaulttimeout(None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1172 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
| 1173 | httpConn.close() |
| 1174 | |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1175 | # no timeout -- do not use global socket default |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 1176 | self.assertIsNone(socket.getdefaulttimeout()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1177 | socket.setdefaulttimeout(30) |
| 1178 | try: |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1179 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 1180 | timeout=None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1181 | httpConn.connect() |
| 1182 | finally: |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1183 | socket.setdefaulttimeout(None) |
| 1184 | self.assertEqual(httpConn.sock.gettimeout(), None) |
| 1185 | httpConn.close() |
| 1186 | |
| 1187 | # a value |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1188 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1189 | httpConn.connect() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1190 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
| 1191 | httpConn.close() |
| 1192 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1193 | |
R David Murray | cae7bdb | 2015-04-05 19:26:29 -0400 | [diff] [blame] | 1194 | class PersistenceTest(TestCase): |
| 1195 | |
| 1196 | def test_reuse_reconnect(self): |
| 1197 | # Should reuse or reconnect depending on header from server |
| 1198 | tests = ( |
| 1199 | ('1.0', '', False), |
| 1200 | ('1.0', 'Connection: keep-alive\r\n', True), |
| 1201 | ('1.1', '', True), |
| 1202 | ('1.1', 'Connection: close\r\n', False), |
| 1203 | ('1.0', 'Connection: keep-ALIVE\r\n', True), |
| 1204 | ('1.1', 'Connection: cloSE\r\n', False), |
| 1205 | ) |
| 1206 | for version, header, reuse in tests: |
| 1207 | with self.subTest(version=version, header=header): |
| 1208 | msg = ( |
| 1209 | 'HTTP/{} 200 OK\r\n' |
| 1210 | '{}' |
| 1211 | 'Content-Length: 12\r\n' |
| 1212 | '\r\n' |
| 1213 | 'Dummy body\r\n' |
| 1214 | ).format(version, header) |
| 1215 | conn = FakeSocketHTTPConnection(msg) |
| 1216 | self.assertIsNone(conn.sock) |
| 1217 | conn.request('GET', '/open-connection') |
| 1218 | with conn.getresponse() as response: |
| 1219 | self.assertEqual(conn.sock is None, not reuse) |
| 1220 | response.read() |
| 1221 | self.assertEqual(conn.sock is None, not reuse) |
| 1222 | self.assertEqual(conn.connections, 1) |
| 1223 | conn.request('GET', '/subsequent-request') |
| 1224 | self.assertEqual(conn.connections, 1 if reuse else 2) |
| 1225 | |
| 1226 | def test_disconnected(self): |
| 1227 | |
| 1228 | def make_reset_reader(text): |
| 1229 | """Return BufferedReader that raises ECONNRESET at EOF""" |
| 1230 | stream = io.BytesIO(text) |
| 1231 | def readinto(buffer): |
| 1232 | size = io.BytesIO.readinto(stream, buffer) |
| 1233 | if size == 0: |
| 1234 | raise ConnectionResetError() |
| 1235 | return size |
| 1236 | stream.readinto = readinto |
| 1237 | return io.BufferedReader(stream) |
| 1238 | |
| 1239 | tests = ( |
| 1240 | (io.BytesIO, client.RemoteDisconnected), |
| 1241 | (make_reset_reader, ConnectionResetError), |
| 1242 | ) |
| 1243 | for stream_factory, exception in tests: |
| 1244 | with self.subTest(exception=exception): |
| 1245 | conn = FakeSocketHTTPConnection(b'', stream_factory) |
| 1246 | conn.request('GET', '/eof-response') |
| 1247 | self.assertRaises(exception, conn.getresponse) |
| 1248 | self.assertIsNone(conn.sock) |
| 1249 | # HTTPConnection.connect() should be automatically invoked |
| 1250 | conn.request('GET', '/reconnect') |
| 1251 | self.assertEqual(conn.connections, 2) |
| 1252 | |
| 1253 | def test_100_close(self): |
| 1254 | conn = FakeSocketHTTPConnection( |
| 1255 | b'HTTP/1.1 100 Continue\r\n' |
| 1256 | b'\r\n' |
| 1257 | # Missing final response |
| 1258 | ) |
| 1259 | conn.request('GET', '/', headers={'Expect': '100-continue'}) |
| 1260 | self.assertRaises(client.RemoteDisconnected, conn.getresponse) |
| 1261 | self.assertIsNone(conn.sock) |
| 1262 | conn.request('GET', '/reconnect') |
| 1263 | self.assertEqual(conn.connections, 2) |
| 1264 | |
| 1265 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1266 | class HTTPSTest(TestCase): |
| 1267 | |
| 1268 | def setUp(self): |
| 1269 | if not hasattr(client, 'HTTPSConnection'): |
| 1270 | self.skipTest('ssl support required') |
| 1271 | |
| 1272 | def make_server(self, certfile): |
| 1273 | from test.ssl_servers import make_https_server |
Antoine Pitrou | da23259 | 2013-02-05 21:20:51 +0100 | [diff] [blame] | 1274 | return make_https_server(self, certfile=certfile) |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 1275 | |
| 1276 | def test_attributes(self): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1277 | # simple test to check it's storing the timeout |
| 1278 | h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) |
| 1279 | self.assertEqual(h.timeout, 30) |
| 1280 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1281 | def test_networked(self): |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1282 | # Default settings: requires a valid cert from a trusted CA |
| 1283 | import ssl |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1284 | support.requires('network') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1285 | with support.transient_internet('self-signed.pythontest.net'): |
| 1286 | h = client.HTTPSConnection('self-signed.pythontest.net', 443) |
| 1287 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 1288 | h.request('GET', '/') |
| 1289 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 1290 | |
| 1291 | def test_networked_noverification(self): |
| 1292 | # Switch off cert verification |
| 1293 | import ssl |
| 1294 | support.requires('network') |
| 1295 | with support.transient_internet('self-signed.pythontest.net'): |
| 1296 | context = ssl._create_unverified_context() |
| 1297 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, |
| 1298 | context=context) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1299 | h.request('GET', '/') |
| 1300 | resp = h.getresponse() |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1301 | h.close() |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1302 | self.assertIn('nginx', resp.getheader('server')) |
| 1303 | |
Benjamin Peterson | 2615e9e | 2014-11-25 15:16:55 -0600 | [diff] [blame] | 1304 | @support.system_must_validate_cert |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1305 | def test_networked_trusted_by_default_cert(self): |
| 1306 | # Default settings: requires a valid cert from a trusted CA |
| 1307 | support.requires('network') |
| 1308 | with support.transient_internet('www.python.org'): |
| 1309 | h = client.HTTPSConnection('www.python.org', 443) |
| 1310 | h.request('GET', '/') |
| 1311 | resp = h.getresponse() |
| 1312 | content_type = resp.getheader('content-type') |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1313 | h.close() |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1314 | self.assertIn('text/html', content_type) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1315 | |
| 1316 | def test_networked_good_cert(self): |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1317 | # We feed the server's cert as a validating cert |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1318 | import ssl |
| 1319 | support.requires('network') |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1320 | with support.transient_internet('self-signed.pythontest.net'): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1321 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1322 | context.verify_mode = ssl.CERT_REQUIRED |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1323 | context.load_verify_locations(CERT_selfsigned_pythontestdotnet) |
| 1324 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1325 | h.request('GET', '/') |
| 1326 | resp = h.getresponse() |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1327 | server_string = resp.getheader('server') |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1328 | h.close() |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1329 | self.assertIn('nginx', server_string) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1330 | |
| 1331 | def test_networked_bad_cert(self): |
| 1332 | # We feed a "CA" cert that is unrelated to the server's cert |
| 1333 | import ssl |
| 1334 | support.requires('network') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1335 | with support.transient_internet('self-signed.pythontest.net'): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1336 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1337 | context.verify_mode = ssl.CERT_REQUIRED |
| 1338 | context.load_verify_locations(CERT_localhost) |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1339 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
| 1340 | with self.assertRaises(ssl.SSLError) as exc_info: |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1341 | h.request('GET', '/') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1342 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 1343 | |
| 1344 | def test_local_unknown_cert(self): |
| 1345 | # The custom cert isn't known to the default trust bundle |
| 1346 | import ssl |
| 1347 | server = self.make_server(CERT_localhost) |
| 1348 | h = client.HTTPSConnection('localhost', server.port) |
| 1349 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 1350 | h.request('GET', '/') |
| 1351 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1352 | |
| 1353 | def test_local_good_hostname(self): |
| 1354 | # The (valid) cert validates the HTTP hostname |
| 1355 | import ssl |
Brett Cannon | 252365b | 2011-08-04 22:43:11 -0700 | [diff] [blame] | 1356 | server = self.make_server(CERT_localhost) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1357 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1358 | context.verify_mode = ssl.CERT_REQUIRED |
| 1359 | context.load_verify_locations(CERT_localhost) |
| 1360 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1361 | h.request('GET', '/nonexistent') |
| 1362 | resp = h.getresponse() |
| 1363 | self.assertEqual(resp.status, 404) |
| 1364 | |
| 1365 | def test_local_bad_hostname(self): |
| 1366 | # The (valid) cert doesn't validate the HTTP hostname |
| 1367 | import ssl |
Brett Cannon | 252365b | 2011-08-04 22:43:11 -0700 | [diff] [blame] | 1368 | server = self.make_server(CERT_fakehostname) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1369 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1370 | context.verify_mode = ssl.CERT_REQUIRED |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1371 | context.check_hostname = True |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1372 | context.load_verify_locations(CERT_fakehostname) |
| 1373 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1374 | with self.assertRaises(ssl.CertificateError): |
| 1375 | h.request('GET', '/') |
| 1376 | # Same with explicit check_hostname=True |
| 1377 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1378 | check_hostname=True) |
| 1379 | with self.assertRaises(ssl.CertificateError): |
| 1380 | h.request('GET', '/') |
| 1381 | # With check_hostname=False, the mismatching is ignored |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1382 | context.check_hostname = False |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1383 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1384 | check_hostname=False) |
| 1385 | h.request('GET', '/nonexistent') |
| 1386 | resp = h.getresponse() |
| 1387 | self.assertEqual(resp.status, 404) |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1388 | # The context's check_hostname setting is used if one isn't passed to |
| 1389 | # HTTPSConnection. |
| 1390 | context.check_hostname = False |
| 1391 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1392 | h.request('GET', '/nonexistent') |
| 1393 | self.assertEqual(h.getresponse().status, 404) |
| 1394 | # Passing check_hostname to HTTPSConnection should override the |
| 1395 | # context's setting. |
| 1396 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1397 | check_hostname=True) |
| 1398 | with self.assertRaises(ssl.CertificateError): |
| 1399 | h.request('GET', '/') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1400 | |
Petri Lehtinen | e119c40 | 2011-10-26 21:29:15 +0300 | [diff] [blame] | 1401 | @unittest.skipIf(not hasattr(client, 'HTTPSConnection'), |
| 1402 | 'http.client.HTTPSConnection not available') |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 1403 | def test_host_port(self): |
| 1404 | # Check invalid host_port |
| 1405 | |
| 1406 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
| 1407 | self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp) |
| 1408 | |
| 1409 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", |
| 1410 | "fe80::207:e9ff:fe9b", 8000), |
| 1411 | ("www.python.org:443", "www.python.org", 443), |
| 1412 | ("www.python.org:", "www.python.org", 443), |
| 1413 | ("www.python.org", "www.python.org", 443), |
| 1414 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443), |
| 1415 | ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", |
| 1416 | 443)): |
| 1417 | c = client.HTTPSConnection(hp) |
| 1418 | self.assertEqual(h, c.host) |
| 1419 | self.assertEqual(p, c.port) |
| 1420 | |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 1421 | |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1422 | class RequestBodyTest(TestCase): |
| 1423 | """Test cases where a request includes a message body.""" |
| 1424 | |
| 1425 | def setUp(self): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1426 | self.conn = client.HTTPConnection('example.com') |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 1427 | self.conn.sock = self.sock = FakeSocket("") |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1428 | self.conn.sock = self.sock |
| 1429 | |
| 1430 | def get_headers_and_fp(self): |
| 1431 | f = io.BytesIO(self.sock.data) |
| 1432 | f.readline() # read the request line |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1433 | message = client.parse_headers(f) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1434 | return message, f |
| 1435 | |
| 1436 | def test_manual_content_length(self): |
| 1437 | # Set an incorrect content-length so that we can verify that |
| 1438 | # it will not be over-ridden by the library. |
| 1439 | self.conn.request("PUT", "/url", "body", |
| 1440 | {"Content-Length": "42"}) |
| 1441 | message, f = self.get_headers_and_fp() |
| 1442 | self.assertEqual("42", message.get("content-length")) |
| 1443 | self.assertEqual(4, len(f.read())) |
| 1444 | |
| 1445 | def test_ascii_body(self): |
| 1446 | self.conn.request("PUT", "/url", "body") |
| 1447 | message, f = self.get_headers_and_fp() |
| 1448 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1449 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1450 | self.assertEqual("4", message.get("content-length")) |
| 1451 | self.assertEqual(b'body', f.read()) |
| 1452 | |
| 1453 | def test_latin1_body(self): |
| 1454 | self.conn.request("PUT", "/url", "body\xc1") |
| 1455 | message, f = self.get_headers_and_fp() |
| 1456 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1457 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1458 | self.assertEqual("5", message.get("content-length")) |
| 1459 | self.assertEqual(b'body\xc1', f.read()) |
| 1460 | |
| 1461 | def test_bytes_body(self): |
| 1462 | self.conn.request("PUT", "/url", b"body\xc1") |
| 1463 | message, f = self.get_headers_and_fp() |
| 1464 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1465 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1466 | self.assertEqual("5", message.get("content-length")) |
| 1467 | self.assertEqual(b'body\xc1', f.read()) |
| 1468 | |
| 1469 | def test_file_body(self): |
Victor Stinner | 18d15cb | 2011-09-21 01:09:04 +0200 | [diff] [blame] | 1470 | self.addCleanup(support.unlink, support.TESTFN) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1471 | with open(support.TESTFN, "w") as f: |
| 1472 | f.write("body") |
| 1473 | with open(support.TESTFN) as f: |
| 1474 | self.conn.request("PUT", "/url", f) |
| 1475 | message, f = self.get_headers_and_fp() |
| 1476 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1477 | self.assertIsNone(message.get_charset()) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1478 | self.assertEqual("4", message.get("content-length")) |
| 1479 | self.assertEqual(b'body', f.read()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1480 | |
| 1481 | def test_binary_file_body(self): |
Victor Stinner | 18d15cb | 2011-09-21 01:09:04 +0200 | [diff] [blame] | 1482 | self.addCleanup(support.unlink, support.TESTFN) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1483 | with open(support.TESTFN, "wb") as f: |
| 1484 | f.write(b"body\xc1") |
| 1485 | with open(support.TESTFN, "rb") as f: |
| 1486 | self.conn.request("PUT", "/url", f) |
| 1487 | message, f = self.get_headers_and_fp() |
| 1488 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1489 | self.assertIsNone(message.get_charset()) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1490 | self.assertEqual("5", message.get("content-length")) |
| 1491 | self.assertEqual(b'body\xc1', f.read()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1492 | |
Senthil Kumaran | 9f8dc44 | 2010-08-02 11:04:58 +0000 | [diff] [blame] | 1493 | |
| 1494 | class HTTPResponseTest(TestCase): |
| 1495 | |
| 1496 | def setUp(self): |
| 1497 | body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \ |
| 1498 | second-value\r\n\r\nText" |
| 1499 | sock = FakeSocket(body) |
| 1500 | self.resp = client.HTTPResponse(sock) |
| 1501 | self.resp.begin() |
| 1502 | |
| 1503 | def test_getting_header(self): |
| 1504 | header = self.resp.getheader('My-Header') |
| 1505 | self.assertEqual(header, 'first-value, second-value') |
| 1506 | |
| 1507 | header = self.resp.getheader('My-Header', 'some default') |
| 1508 | self.assertEqual(header, 'first-value, second-value') |
| 1509 | |
| 1510 | def test_getting_nonexistent_header_with_string_default(self): |
| 1511 | header = self.resp.getheader('No-Such-Header', 'default-value') |
| 1512 | self.assertEqual(header, 'default-value') |
| 1513 | |
| 1514 | def test_getting_nonexistent_header_with_iterable_default(self): |
| 1515 | header = self.resp.getheader('No-Such-Header', ['default', 'values']) |
| 1516 | self.assertEqual(header, 'default, values') |
| 1517 | |
| 1518 | header = self.resp.getheader('No-Such-Header', ('default', 'values')) |
| 1519 | self.assertEqual(header, 'default, values') |
| 1520 | |
| 1521 | def test_getting_nonexistent_header_without_default(self): |
| 1522 | header = self.resp.getheader('No-Such-Header') |
| 1523 | self.assertEqual(header, None) |
| 1524 | |
| 1525 | def test_getting_header_defaultint(self): |
| 1526 | header = self.resp.getheader('No-Such-Header',default=42) |
| 1527 | self.assertEqual(header, 42) |
| 1528 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1529 | class TunnelTests(TestCase): |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1530 | def setUp(self): |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1531 | response_text = ( |
| 1532 | 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT |
| 1533 | 'HTTP/1.1 200 OK\r\n' # Reply to HEAD |
| 1534 | 'Content-Length: 42\r\n\r\n' |
| 1535 | ) |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1536 | self.host = 'proxy.com' |
| 1537 | self.conn = client.HTTPConnection(self.host) |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1538 | self.conn._create_connection = self._create_connection(response_text) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1539 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1540 | def tearDown(self): |
| 1541 | self.conn.close() |
| 1542 | |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1543 | def _create_connection(self, response_text): |
| 1544 | def create_connection(address, timeout=None, source_address=None): |
| 1545 | return FakeSocket(response_text, host=address[0], port=address[1]) |
| 1546 | return create_connection |
| 1547 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1548 | def test_set_tunnel_host_port_headers(self): |
| 1549 | tunnel_host = 'destination.com' |
| 1550 | tunnel_port = 8888 |
| 1551 | tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'} |
| 1552 | self.conn.set_tunnel(tunnel_host, port=tunnel_port, |
| 1553 | headers=tunnel_headers) |
| 1554 | self.conn.request('HEAD', '/', '') |
| 1555 | self.assertEqual(self.conn.sock.host, self.host) |
| 1556 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1557 | self.assertEqual(self.conn._tunnel_host, tunnel_host) |
| 1558 | self.assertEqual(self.conn._tunnel_port, tunnel_port) |
| 1559 | self.assertEqual(self.conn._tunnel_headers, tunnel_headers) |
| 1560 | |
| 1561 | def test_disallow_set_tunnel_after_connect(self): |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1562 | # Once connected, we shouldn't be able to tunnel anymore |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1563 | self.conn.connect() |
| 1564 | self.assertRaises(RuntimeError, self.conn.set_tunnel, |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1565 | 'destination.com') |
| 1566 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1567 | def test_connect_with_tunnel(self): |
| 1568 | self.conn.set_tunnel('destination.com') |
| 1569 | self.conn.request('HEAD', '/', '') |
| 1570 | self.assertEqual(self.conn.sock.host, self.host) |
| 1571 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1572 | self.assertIn(b'CONNECT destination.com', self.conn.sock.data) |
Serhiy Storchaka | 4ac7ed9 | 2014-12-12 09:29:15 +0200 | [diff] [blame] | 1573 | # issue22095 |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1574 | self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data) |
| 1575 | self.assertIn(b'Host: destination.com', self.conn.sock.data) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1576 | |
| 1577 | # This test should be removed when CONNECT gets the HTTP/1.1 blessing |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1578 | self.assertNotIn(b'Host: proxy.com', self.conn.sock.data) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1579 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1580 | def test_connect_put_request(self): |
| 1581 | self.conn.set_tunnel('destination.com') |
| 1582 | self.conn.request('PUT', '/', '') |
| 1583 | self.assertEqual(self.conn.sock.host, self.host) |
| 1584 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1585 | self.assertIn(b'CONNECT destination.com', self.conn.sock.data) |
| 1586 | self.assertIn(b'Host: destination.com', self.conn.sock.data) |
| 1587 | |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1588 | def test_tunnel_debuglog(self): |
| 1589 | expected_header = 'X-Dummy: 1' |
| 1590 | response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header) |
| 1591 | |
| 1592 | self.conn.set_debuglevel(1) |
| 1593 | self.conn._create_connection = self._create_connection(response_text) |
| 1594 | self.conn.set_tunnel('destination.com') |
| 1595 | |
| 1596 | with support.captured_stdout() as output: |
| 1597 | self.conn.request('PUT', '/', '') |
| 1598 | lines = output.getvalue().splitlines() |
| 1599 | self.assertIn('header: {}'.format(expected_header), lines) |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1600 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1601 | |
Benjamin Peterson | 9566de1 | 2014-12-13 16:13:24 -0500 | [diff] [blame] | 1602 | @support.reap_threads |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 1603 | def test_main(verbose=None): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1604 | support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, |
R David Murray | cae7bdb | 2015-04-05 19:26:29 -0400 | [diff] [blame] | 1605 | PersistenceTest, |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1606 | HTTPSTest, RequestBodyTest, SourceAddressTest, |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 1607 | HTTPResponseTest, ExtendedReadTest, |
Senthil Kumaran | 166214c | 2014-04-14 13:10:05 -0400 | [diff] [blame] | 1608 | ExtendedReadTestChunked, TunnelTests) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 1609 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1610 | if __name__ == '__main__': |
| 1611 | test_main() |