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