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