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