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