blob: e9272569ecc531197901ddcb017dedd3cafdde56 [file] [log] [blame]
Ethan Furmana02cb472021-04-21 10:20:44 -07001import enum
Jeremy Hylton636950f2009-03-28 04:34:21 +00002import errno
Angelin BOOZ68526fe2020-09-21 15:11:06 +02003from http import client, HTTPStatus
Jeremy Hylton8fff7922007-08-03 20:56:14 +00004import io
R David Murraybeed8402015-03-22 15:18:23 -04005import itertools
Antoine Pitrou803e6d62010-10-13 10:36:15 +00006import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00007import array
Gregory P. Smith2cc02232019-05-06 17:54:06 -04008import re
Guido van Rossumd8faa362007-04-27 19:54:29 +00009import socket
Antoine Pitrou88c60c92017-09-18 23:50:44 +020010import threading
Pablo Galindoaa542c22019-08-08 23:25:46 +010011import warnings
Jeremy Hylton121d34a2003-07-08 12:36:58 +000012
Gregory P. Smithb4066372010-01-03 03:28:29 +000013import unittest
Gregory P. Smithc25910a2021-03-07 23:35:13 -080014from unittest import mock
Gregory P. Smithb4066372010-01-03 03:28:29 +000015TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000016
Benjamin Petersonee8712c2008-05-20 21:35:26 +000017from test import support
Hai Shi883bc632020-07-06 17:12:49 +080018from test.support import os_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030019from test.support import socket_helper
Hai Shi883bc632020-07-06 17:12:49 +080020from test.support import warnings_helper
21
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000022
Antoine Pitrou803e6d62010-10-13 10:36:15 +000023here = os.path.dirname(__file__)
24# Self-signed cert file for 'localhost'
25CERT_localhost = os.path.join(here, 'keycert.pem')
26# Self-signed cert file for 'fakehostname'
27CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010028# Self-signed cert file for self-signed.pythontest.net
29CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000030
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000031# constants for testing chunked encoding
32chunked_start = (
33 'HTTP/1.1 200 OK\r\n'
34 'Transfer-Encoding: chunked\r\n\r\n'
35 'a\r\n'
36 'hello worl\r\n'
37 '3\r\n'
38 'd! \r\n'
39 '8\r\n'
40 'and now \r\n'
41 '22\r\n'
42 'for something completely different\r\n'
43)
44chunked_expected = b'hello world! and now for something completely different'
45chunk_extension = ";foo=bar"
46last_chunk = "0\r\n"
47last_chunk_extended = "0" + chunk_extension + "\r\n"
48trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
49chunked_end = "\r\n"
50
Serhiy Storchaka16994912020-04-25 10:06:29 +030051HOST = socket_helper.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000052
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000053class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040054 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000055 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000056 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000057 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000058 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000059 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010060 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020061 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040062 self.host = host
63 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000064
Jeremy Hylton2c178252004-08-07 16:28:14 +000065 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010066 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000067 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000068
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000069 def makefile(self, mode, bufsize=None):
70 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000071 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000072 # keep the file around so we can check how much was read from it
73 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020074 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000075 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000076
Serhiy Storchakab491e052014-12-01 13:07:45 +020077 def file_close(self):
78 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000079
Senthil Kumaran9da047b2014-04-14 13:07:56 -040080 def close(self):
81 pass
82
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050083 def setsockopt(self, level, optname, value):
84 pass
85
Jeremy Hylton636950f2009-03-28 04:34:21 +000086class EPipeSocket(FakeSocket):
87
88 def __init__(self, text, pipe_trigger):
89 # When sendall() is called with pipe_trigger, raise EPIPE.
90 FakeSocket.__init__(self, text)
91 self.pipe_trigger = pipe_trigger
92
93 def sendall(self, data):
94 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020095 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000096 self.data += data
97
98 def close(self):
99 pass
100
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300101class NoEOFBytesIO(io.BytesIO):
102 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000103
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000104 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000105 more from the underlying file than it should.
106 """
107 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000108 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000109 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000110 raise AssertionError('caller tried to read past EOF')
111 return data
112
113 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000114 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000115 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000116 raise AssertionError('caller tried to read past EOF')
117 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000118
R David Murraycae7bdb2015-04-05 19:26:29 -0400119class FakeSocketHTTPConnection(client.HTTPConnection):
120 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
121
122 def __init__(self, *args):
123 self.connections = 0
124 super().__init__('example.com')
125 self.fake_socket_args = args
126 self._create_connection = self.create_connection
127
128 def connect(self):
129 """Count the number of times connect() is invoked"""
130 self.connections += 1
131 return super().connect()
132
133 def create_connection(self, *pos, **kw):
134 return FakeSocket(*self.fake_socket_args)
135
Jeremy Hylton2c178252004-08-07 16:28:14 +0000136class HeaderTests(TestCase):
137 def test_auto_headers(self):
138 # Some headers are added automatically, but should not be added by
139 # .request() if they are explicitly set.
140
Jeremy Hylton2c178252004-08-07 16:28:14 +0000141 class HeaderCountingBuffer(list):
142 def __init__(self):
143 self.count = {}
144 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000145 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000146 if len(kv) > 1:
147 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000148 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000149 self.count.setdefault(lcKey, 0)
150 self.count[lcKey] += 1
151 list.append(self, item)
152
153 for explicit_header in True, False:
154 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000155 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000156 conn.sock = FakeSocket('blahblahblah')
157 conn._buffer = HeaderCountingBuffer()
158
159 body = 'spamspamspam'
160 headers = {}
161 if explicit_header:
162 headers[header] = str(len(body))
163 conn.request('POST', '/', body, headers)
164 self.assertEqual(conn._buffer.count[header.lower()], 1)
165
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800166 def test_content_length_0(self):
167
168 class ContentLengthChecker(list):
169 def __init__(self):
170 list.__init__(self)
171 self.content_length = None
172 def append(self, item):
173 kv = item.split(b':', 1)
174 if len(kv) > 1 and kv[0].lower() == b'content-length':
175 self.content_length = kv[1].strip()
176 list.append(self, item)
177
R David Murraybeed8402015-03-22 15:18:23 -0400178 # Here, we're testing that methods expecting a body get a
179 # content-length set to zero if the body is empty (either None or '')
180 bodies = (None, '')
181 methods_with_body = ('PUT', 'POST', 'PATCH')
182 for method, body in itertools.product(methods_with_body, bodies):
183 conn = client.HTTPConnection('example.com')
184 conn.sock = FakeSocket(None)
185 conn._buffer = ContentLengthChecker()
186 conn.request(method, '/', body)
187 self.assertEqual(
188 conn._buffer.content_length, b'0',
189 'Header Content-Length incorrect on {}'.format(method)
190 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800191
R David Murraybeed8402015-03-22 15:18:23 -0400192 # For these methods, we make sure that content-length is not set when
193 # the body is None because it might cause unexpected behaviour on the
194 # server.
195 methods_without_body = (
196 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
197 )
198 for method in methods_without_body:
199 conn = client.HTTPConnection('example.com')
200 conn.sock = FakeSocket(None)
201 conn._buffer = ContentLengthChecker()
202 conn.request(method, '/', None)
203 self.assertEqual(
204 conn._buffer.content_length, None,
205 'Header Content-Length set for empty body on {}'.format(method)
206 )
207
208 # If the body is set to '', that's considered to be "present but
209 # empty" rather than "missing", so content length would be set, even
210 # for methods that don't expect a body.
211 for method in methods_without_body:
212 conn = client.HTTPConnection('example.com')
213 conn.sock = FakeSocket(None)
214 conn._buffer = ContentLengthChecker()
215 conn.request(method, '/', '')
216 self.assertEqual(
217 conn._buffer.content_length, b'0',
218 'Header Content-Length incorrect on {}'.format(method)
219 )
220
221 # If the body is set, make sure Content-Length is set.
222 for method in itertools.chain(methods_without_body, methods_with_body):
223 conn = client.HTTPConnection('example.com')
224 conn.sock = FakeSocket(None)
225 conn._buffer = ContentLengthChecker()
226 conn.request(method, '/', ' ')
227 self.assertEqual(
228 conn._buffer.content_length, b'1',
229 'Header Content-Length incorrect on {}'.format(method)
230 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800231
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000232 def test_putheader(self):
233 conn = client.HTTPConnection('example.com')
234 conn.sock = FakeSocket(None)
235 conn.putrequest('GET','/')
236 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200237 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000238
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200239 conn.putheader('Foo', ' bar ')
240 self.assertIn(b'Foo: bar ', conn._buffer)
241 conn.putheader('Bar', '\tbaz\t')
242 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
243 conn.putheader('Authorization', 'Bearer mytoken')
244 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
245 conn.putheader('IterHeader', 'IterA', 'IterB')
246 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
247 conn.putheader('LatinHeader', b'\xFF')
248 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
249 conn.putheader('Utf8Header', b'\xc3\x80')
250 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
251 conn.putheader('C1-Control', b'next\x85line')
252 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
253 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
254 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
255 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
256 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
257 conn.putheader('Key Space', 'value')
258 self.assertIn(b'Key Space: value', conn._buffer)
259 conn.putheader('KeySpace ', 'value')
260 self.assertIn(b'KeySpace : value', conn._buffer)
261 conn.putheader(b'Nonbreak\xa0Space', 'value')
262 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
263 conn.putheader(b'\xa0NonbreakSpace', 'value')
264 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
265
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000266 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000267 # Default host header on IPv6 transaction should be wrapped by [] if
268 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000269 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
270 b'Accept-Encoding: identity\r\n\r\n'
271 conn = client.HTTPConnection('[2001::]:81')
272 sock = FakeSocket('')
273 conn.sock = sock
274 conn.request('GET', '/foo')
275 self.assertTrue(sock.data.startswith(expected))
276
277 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
278 b'Accept-Encoding: identity\r\n\r\n'
279 conn = client.HTTPConnection('[2001:102A::]')
280 sock = FakeSocket('')
281 conn.sock = sock
282 conn.request('GET', '/foo')
283 self.assertTrue(sock.data.startswith(expected))
284
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500285 def test_malformed_headers_coped_with(self):
286 # Issue 19996
287 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
288 sock = FakeSocket(body)
289 resp = client.HTTPResponse(sock)
290 resp.begin()
291
292 self.assertEqual(resp.getheader('First'), 'val')
293 self.assertEqual(resp.getheader('Second'), 'val')
294
R David Murraydc1650c2016-09-07 17:44:34 -0400295 def test_parse_all_octets(self):
296 # Ensure no valid header field octet breaks the parser
297 body = (
298 b'HTTP/1.1 200 OK\r\n'
299 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
300 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
301 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
302 b'obs-fold: text\r\n'
303 b' folded with space\r\n'
304 b'\tfolded with tab\r\n'
305 b'Content-Length: 0\r\n'
306 b'\r\n'
307 )
308 sock = FakeSocket(body)
309 resp = client.HTTPResponse(sock)
310 resp.begin()
311 self.assertEqual(resp.getheader('Content-Length'), '0')
312 self.assertEqual(resp.msg['Content-Length'], '0')
313 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
314 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
315 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
316 self.assertEqual(resp.getheader('VCHAR'), vchar)
317 self.assertEqual(resp.msg['VCHAR'], vchar)
318 self.assertIsNotNone(resp.getheader('obs-text'))
319 self.assertIn('obs-text', resp.msg)
320 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
321 self.assertTrue(folded.startswith('text'))
322 self.assertIn(' folded with space', folded)
323 self.assertTrue(folded.endswith('folded with tab'))
324
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200325 def test_invalid_headers(self):
326 conn = client.HTTPConnection('example.com')
327 conn.sock = FakeSocket('')
328 conn.putrequest('GET', '/')
329
330 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
331 # longer allowed in header names
332 cases = (
333 (b'Invalid\r\nName', b'ValidValue'),
334 (b'Invalid\rName', b'ValidValue'),
335 (b'Invalid\nName', b'ValidValue'),
336 (b'\r\nInvalidName', b'ValidValue'),
337 (b'\rInvalidName', b'ValidValue'),
338 (b'\nInvalidName', b'ValidValue'),
339 (b' InvalidName', b'ValidValue'),
340 (b'\tInvalidName', b'ValidValue'),
341 (b'Invalid:Name', b'ValidValue'),
342 (b':InvalidName', b'ValidValue'),
343 (b'ValidName', b'Invalid\r\nValue'),
344 (b'ValidName', b'Invalid\rValue'),
345 (b'ValidName', b'Invalid\nValue'),
346 (b'ValidName', b'InvalidValue\r\n'),
347 (b'ValidName', b'InvalidValue\r'),
348 (b'ValidName', b'InvalidValue\n'),
349 )
350 for name, value in cases:
351 with self.subTest((name, value)):
352 with self.assertRaisesRegex(ValueError, 'Invalid header'):
353 conn.putheader(name, value)
354
Marco Strigl936f03e2018-06-19 15:20:58 +0200355 def test_headers_debuglevel(self):
356 body = (
357 b'HTTP/1.1 200 OK\r\n'
358 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700359 b'Second: val1\r\n'
360 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200361 )
362 sock = FakeSocket(body)
363 resp = client.HTTPResponse(sock, debuglevel=1)
364 with support.captured_stdout() as output:
365 resp.begin()
366 lines = output.getvalue().splitlines()
367 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
368 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700369 self.assertEqual(lines[2], "header: Second: val1")
370 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200371
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000372
AMIR8ca8a2e2020-07-19 00:46:10 +0430373class HttpMethodTests(TestCase):
374 def test_invalid_method_names(self):
375 methods = (
376 'GET\r',
377 'POST\n',
378 'PUT\n\r',
379 'POST\nValue',
380 'POST\nHOST:abc',
381 'GET\nrHost:abc\n',
382 'POST\rRemainder:\r',
383 'GET\rHOST:\n',
384 '\nPUT'
385 )
386
387 for method in methods:
388 with self.assertRaisesRegex(
389 ValueError, "method can't contain control characters"):
390 conn = client.HTTPConnection('example.com')
391 conn.sock = FakeSocket(None)
392 conn.request(method=method, url="/")
393
394
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000395class TransferEncodingTest(TestCase):
396 expected_body = b"It's just a flesh wound"
397
398 def test_endheaders_chunked(self):
399 conn = client.HTTPConnection('example.com')
400 conn.sock = FakeSocket(b'')
401 conn.putrequest('POST', '/')
402 conn.endheaders(self._make_body(), encode_chunked=True)
403
404 _, _, body = self._parse_request(conn.sock.data)
405 body = self._parse_chunked(body)
406 self.assertEqual(body, self.expected_body)
407
408 def test_explicit_headers(self):
409 # explicit chunked
410 conn = client.HTTPConnection('example.com')
411 conn.sock = FakeSocket(b'')
412 # this shouldn't actually be automatically chunk-encoded because the
413 # calling code has explicitly stated that it's taking care of it
414 conn.request(
415 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
416
417 _, headers, body = self._parse_request(conn.sock.data)
418 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
419 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
420 self.assertEqual(body, self.expected_body)
421
422 # explicit chunked, string body
423 conn = client.HTTPConnection('example.com')
424 conn.sock = FakeSocket(b'')
425 conn.request(
426 'POST', '/', self.expected_body.decode('latin-1'),
427 {'Transfer-Encoding': 'chunked'})
428
429 _, headers, body = self._parse_request(conn.sock.data)
430 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
431 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
432 self.assertEqual(body, self.expected_body)
433
434 # User-specified TE, but request() does the chunk encoding
435 conn = client.HTTPConnection('example.com')
436 conn.sock = FakeSocket(b'')
437 conn.request('POST', '/',
438 headers={'Transfer-Encoding': 'gzip, chunked'},
439 encode_chunked=True,
440 body=self._make_body())
441 _, headers, body = self._parse_request(conn.sock.data)
442 self.assertNotIn('content-length', [k.lower() for k in headers])
443 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
444 self.assertEqual(self._parse_chunked(body), self.expected_body)
445
446 def test_request(self):
447 for empty_lines in (False, True,):
448 conn = client.HTTPConnection('example.com')
449 conn.sock = FakeSocket(b'')
450 conn.request(
451 'POST', '/', self._make_body(empty_lines=empty_lines))
452
453 _, headers, body = self._parse_request(conn.sock.data)
454 body = self._parse_chunked(body)
455 self.assertEqual(body, self.expected_body)
456 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
457
458 # Content-Length and Transfer-Encoding SHOULD not be sent in the
459 # same request
460 self.assertNotIn('content-length', [k.lower() for k in headers])
461
Martin Panteref91bb22016-08-27 01:39:26 +0000462 def test_empty_body(self):
463 # Zero-length iterable should be treated like any other iterable
464 conn = client.HTTPConnection('example.com')
465 conn.sock = FakeSocket(b'')
466 conn.request('POST', '/', ())
467 _, headers, body = self._parse_request(conn.sock.data)
468 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
469 self.assertNotIn('content-length', [k.lower() for k in headers])
470 self.assertEqual(body, b"0\r\n\r\n")
471
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000472 def _make_body(self, empty_lines=False):
473 lines = self.expected_body.split(b' ')
474 for idx, line in enumerate(lines):
475 # for testing handling empty lines
476 if empty_lines and idx % 2:
477 yield b''
478 if idx < len(lines) - 1:
479 yield line + b' '
480 else:
481 yield line
482
483 def _parse_request(self, data):
484 lines = data.split(b'\r\n')
485 request = lines[0]
486 headers = {}
487 n = 1
488 while n < len(lines) and len(lines[n]) > 0:
489 key, val = lines[n].split(b':')
490 key = key.decode('latin-1').strip()
491 headers[key] = val.decode('latin-1').strip()
492 n += 1
493
494 return request, headers, b'\r\n'.join(lines[n + 1:])
495
496 def _parse_chunked(self, data):
497 body = []
498 trailers = {}
499 n = 0
500 lines = data.split(b'\r\n')
501 # parse body
502 while True:
503 size, chunk = lines[n:n+2]
504 size = int(size, 16)
505
506 if size == 0:
507 n += 1
508 break
509
510 self.assertEqual(size, len(chunk))
511 body.append(chunk)
512
513 n += 2
514 # we /should/ hit the end chunk, but check against the size of
515 # lines so we're not stuck in an infinite loop should we get
516 # malformed data
517 if n > len(lines):
518 break
519
520 return b''.join(body)
521
522
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523class BasicTest(TestCase):
Angelin BOOZ68526fe2020-09-21 15:11:06 +0200524 def test_dir_with_added_behavior_on_status(self):
525 # see issue40084
526 self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
527
Ethan Furmana02cb472021-04-21 10:20:44 -0700528 def test_simple_httpstatus(self):
529 class CheckedHTTPStatus(enum.IntEnum):
530 """HTTP status codes and reason phrases
531
532 Status codes from the following RFCs are all observed:
533
534 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
535 * RFC 6585: Additional HTTP Status Codes
536 * RFC 3229: Delta encoding in HTTP
537 * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
538 * RFC 5842: Binding Extensions to WebDAV
539 * RFC 7238: Permanent Redirect
540 * RFC 2295: Transparent Content Negotiation in HTTP
541 * RFC 2774: An HTTP Extension Framework
542 * RFC 7725: An HTTP Status Code to Report Legal Obstacles
543 * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
544 * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)
545 * RFC 8297: An HTTP Status Code for Indicating Hints
546 * RFC 8470: Using Early Data in HTTP
547 """
548 def __new__(cls, value, phrase, description=''):
549 obj = int.__new__(cls, value)
550 obj._value_ = value
551
552 obj.phrase = phrase
553 obj.description = description
554 return obj
555 # informational
556 CONTINUE = 100, 'Continue', 'Request received, please continue'
557 SWITCHING_PROTOCOLS = (101, 'Switching Protocols',
558 'Switching to new protocol; obey Upgrade header')
559 PROCESSING = 102, 'Processing'
560 EARLY_HINTS = 103, 'Early Hints'
561 # success
562 OK = 200, 'OK', 'Request fulfilled, document follows'
563 CREATED = 201, 'Created', 'Document created, URL follows'
564 ACCEPTED = (202, 'Accepted',
565 'Request accepted, processing continues off-line')
566 NON_AUTHORITATIVE_INFORMATION = (203,
567 'Non-Authoritative Information', 'Request fulfilled from cache')
568 NO_CONTENT = 204, 'No Content', 'Request fulfilled, nothing follows'
569 RESET_CONTENT = 205, 'Reset Content', 'Clear input form for further input'
570 PARTIAL_CONTENT = 206, 'Partial Content', 'Partial content follows'
571 MULTI_STATUS = 207, 'Multi-Status'
572 ALREADY_REPORTED = 208, 'Already Reported'
573 IM_USED = 226, 'IM Used'
574 # redirection
575 MULTIPLE_CHOICES = (300, 'Multiple Choices',
576 'Object has several resources -- see URI list')
577 MOVED_PERMANENTLY = (301, 'Moved Permanently',
578 'Object moved permanently -- see URI list')
579 FOUND = 302, 'Found', 'Object moved temporarily -- see URI list'
580 SEE_OTHER = 303, 'See Other', 'Object moved -- see Method and URL list'
581 NOT_MODIFIED = (304, 'Not Modified',
582 'Document has not changed since given time')
583 USE_PROXY = (305, 'Use Proxy',
584 'You must use proxy specified in Location to access this resource')
585 TEMPORARY_REDIRECT = (307, 'Temporary Redirect',
586 'Object moved temporarily -- see URI list')
587 PERMANENT_REDIRECT = (308, 'Permanent Redirect',
588 'Object moved permanently -- see URI list')
589 # client error
590 BAD_REQUEST = (400, 'Bad Request',
591 'Bad request syntax or unsupported method')
592 UNAUTHORIZED = (401, 'Unauthorized',
593 'No permission -- see authorization schemes')
594 PAYMENT_REQUIRED = (402, 'Payment Required',
595 'No payment -- see charging schemes')
596 FORBIDDEN = (403, 'Forbidden',
597 'Request forbidden -- authorization will not help')
598 NOT_FOUND = (404, 'Not Found',
599 'Nothing matches the given URI')
600 METHOD_NOT_ALLOWED = (405, 'Method Not Allowed',
601 'Specified method is invalid for this resource')
602 NOT_ACCEPTABLE = (406, 'Not Acceptable',
603 'URI not available in preferred format')
604 PROXY_AUTHENTICATION_REQUIRED = (407,
605 'Proxy Authentication Required',
606 'You must authenticate with this proxy before proceeding')
607 REQUEST_TIMEOUT = (408, 'Request Timeout',
608 'Request timed out; try again later')
609 CONFLICT = 409, 'Conflict', 'Request conflict'
610 GONE = (410, 'Gone',
611 'URI no longer exists and has been permanently removed')
612 LENGTH_REQUIRED = (411, 'Length Required',
613 'Client must specify Content-Length')
614 PRECONDITION_FAILED = (412, 'Precondition Failed',
615 'Precondition in headers is false')
616 REQUEST_ENTITY_TOO_LARGE = (413, 'Request Entity Too Large',
617 'Entity is too large')
618 REQUEST_URI_TOO_LONG = (414, 'Request-URI Too Long',
619 'URI is too long')
620 UNSUPPORTED_MEDIA_TYPE = (415, 'Unsupported Media Type',
621 'Entity body in unsupported format')
622 REQUESTED_RANGE_NOT_SATISFIABLE = (416,
623 'Requested Range Not Satisfiable',
624 'Cannot satisfy request range')
625 EXPECTATION_FAILED = (417, 'Expectation Failed',
626 'Expect condition could not be satisfied')
627 IM_A_TEAPOT = (418, 'I\'m a Teapot',
628 'Server refuses to brew coffee because it is a teapot.')
629 MISDIRECTED_REQUEST = (421, 'Misdirected Request',
630 'Server is not able to produce a response')
631 UNPROCESSABLE_ENTITY = 422, 'Unprocessable Entity'
632 LOCKED = 423, 'Locked'
633 FAILED_DEPENDENCY = 424, 'Failed Dependency'
634 TOO_EARLY = 425, 'Too Early'
635 UPGRADE_REQUIRED = 426, 'Upgrade Required'
636 PRECONDITION_REQUIRED = (428, 'Precondition Required',
637 'The origin server requires the request to be conditional')
638 TOO_MANY_REQUESTS = (429, 'Too Many Requests',
639 'The user has sent too many requests in '
640 'a given amount of time ("rate limiting")')
641 REQUEST_HEADER_FIELDS_TOO_LARGE = (431,
642 'Request Header Fields Too Large',
643 'The server is unwilling to process the request because its header '
644 'fields are too large')
645 UNAVAILABLE_FOR_LEGAL_REASONS = (451,
646 'Unavailable For Legal Reasons',
647 'The server is denying access to the '
648 'resource as a consequence of a legal demand')
649 # server errors
650 INTERNAL_SERVER_ERROR = (500, 'Internal Server Error',
651 'Server got itself in trouble')
652 NOT_IMPLEMENTED = (501, 'Not Implemented',
653 'Server does not support this operation')
654 BAD_GATEWAY = (502, 'Bad Gateway',
655 'Invalid responses from another server/proxy')
656 SERVICE_UNAVAILABLE = (503, 'Service Unavailable',
657 'The server cannot process the request due to a high load')
658 GATEWAY_TIMEOUT = (504, 'Gateway Timeout',
659 'The gateway server did not receive a timely response')
660 HTTP_VERSION_NOT_SUPPORTED = (505, 'HTTP Version Not Supported',
661 'Cannot fulfill request')
662 VARIANT_ALSO_NEGOTIATES = 506, 'Variant Also Negotiates'
663 INSUFFICIENT_STORAGE = 507, 'Insufficient Storage'
664 LOOP_DETECTED = 508, 'Loop Detected'
665 NOT_EXTENDED = 510, 'Not Extended'
666 NETWORK_AUTHENTICATION_REQUIRED = (511,
667 'Network Authentication Required',
668 'The client needs to authenticate to gain network access')
669 enum._test_simple_enum(CheckedHTTPStatus, HTTPStatus)
670
671
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 def test_status_lines(self):
673 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000674
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675 body = "HTTP/1.1 200 Ok\r\n\r\nText"
676 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000677 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000678 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200679 self.assertEqual(resp.read(0), b'') # Issue #20007
680 self.assertFalse(resp.isclosed())
681 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000682 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000683 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200684 self.assertFalse(resp.closed)
685 resp.close()
686 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000687
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
689 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000690 resp = client.HTTPResponse(sock)
691 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000692
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000693 def test_bad_status_repr(self):
694 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200695 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000696
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000697 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000698 # if we have Content-Length, HTTPResponse knows when to close itself,
699 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000700 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
701 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000702 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000703 resp.begin()
704 self.assertEqual(resp.read(2), b'Te')
705 self.assertFalse(resp.isclosed())
706 self.assertEqual(resp.read(2), b'xt')
707 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200708 self.assertFalse(resp.closed)
709 resp.close()
710 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000711
Martin Panterce911c32016-03-17 06:42:48 +0000712 def test_mixed_reads(self):
713 # readline() should update the remaining length, so that read() knows
714 # how much data is left and does not raise IncompleteRead
715 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
716 sock = FakeSocket(body)
717 resp = client.HTTPResponse(sock)
718 resp.begin()
719 self.assertEqual(resp.readline(), b'Text\r\n')
720 self.assertFalse(resp.isclosed())
721 self.assertEqual(resp.read(), b'Another')
722 self.assertTrue(resp.isclosed())
723 self.assertFalse(resp.closed)
724 resp.close()
725 self.assertTrue(resp.closed)
726
Antoine Pitrou38d96432011-12-06 22:33:57 +0100727 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000728 # if we have Content-Length, HTTPResponse knows when to close itself,
729 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100730 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
731 sock = FakeSocket(body)
732 resp = client.HTTPResponse(sock)
733 resp.begin()
734 b = bytearray(2)
735 n = resp.readinto(b)
736 self.assertEqual(n, 2)
737 self.assertEqual(bytes(b), b'Te')
738 self.assertFalse(resp.isclosed())
739 n = resp.readinto(b)
740 self.assertEqual(n, 2)
741 self.assertEqual(bytes(b), b'xt')
742 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200743 self.assertFalse(resp.closed)
744 resp.close()
745 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100746
Bruce Merry152f0b82020-06-25 08:30:21 +0200747 def test_partial_reads_past_end(self):
748 # if we have Content-Length, clip reads to the end
749 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
750 sock = FakeSocket(body)
751 resp = client.HTTPResponse(sock)
752 resp.begin()
753 self.assertEqual(resp.read(10), b'Text')
754 self.assertTrue(resp.isclosed())
755 self.assertFalse(resp.closed)
756 resp.close()
757 self.assertTrue(resp.closed)
758
759 def test_partial_readintos_past_end(self):
760 # if we have Content-Length, clip readintos to the end
761 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
762 sock = FakeSocket(body)
763 resp = client.HTTPResponse(sock)
764 resp.begin()
765 b = bytearray(10)
766 n = resp.readinto(b)
767 self.assertEqual(n, 4)
768 self.assertEqual(bytes(b)[:4], b'Text')
769 self.assertTrue(resp.isclosed())
770 self.assertFalse(resp.closed)
771 resp.close()
772 self.assertTrue(resp.closed)
773
Antoine Pitrou084daa22012-12-15 19:11:54 +0100774 def test_partial_reads_no_content_length(self):
775 # when no length is present, the socket should be gracefully closed when
776 # all data was read
777 body = "HTTP/1.1 200 Ok\r\n\r\nText"
778 sock = FakeSocket(body)
779 resp = client.HTTPResponse(sock)
780 resp.begin()
781 self.assertEqual(resp.read(2), b'Te')
782 self.assertFalse(resp.isclosed())
783 self.assertEqual(resp.read(2), b'xt')
784 self.assertEqual(resp.read(1), b'')
785 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200786 self.assertFalse(resp.closed)
787 resp.close()
788 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100789
Antoine Pitroud20e7742012-12-15 19:22:30 +0100790 def test_partial_readintos_no_content_length(self):
791 # when no length is present, the socket should be gracefully closed when
792 # all data was read
793 body = "HTTP/1.1 200 Ok\r\n\r\nText"
794 sock = FakeSocket(body)
795 resp = client.HTTPResponse(sock)
796 resp.begin()
797 b = bytearray(2)
798 n = resp.readinto(b)
799 self.assertEqual(n, 2)
800 self.assertEqual(bytes(b), b'Te')
801 self.assertFalse(resp.isclosed())
802 n = resp.readinto(b)
803 self.assertEqual(n, 2)
804 self.assertEqual(bytes(b), b'xt')
805 n = resp.readinto(b)
806 self.assertEqual(n, 0)
807 self.assertTrue(resp.isclosed())
808
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100809 def test_partial_reads_incomplete_body(self):
810 # if the server shuts down the connection before the whole
811 # content-length is delivered, the socket is gracefully closed
812 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
813 sock = FakeSocket(body)
814 resp = client.HTTPResponse(sock)
815 resp.begin()
816 self.assertEqual(resp.read(2), b'Te')
817 self.assertFalse(resp.isclosed())
818 self.assertEqual(resp.read(2), b'xt')
819 self.assertEqual(resp.read(1), b'')
820 self.assertTrue(resp.isclosed())
821
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100822 def test_partial_readintos_incomplete_body(self):
823 # if the server shuts down the connection before the whole
824 # content-length is delivered, the socket is gracefully closed
825 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
826 sock = FakeSocket(body)
827 resp = client.HTTPResponse(sock)
828 resp.begin()
829 b = bytearray(2)
830 n = resp.readinto(b)
831 self.assertEqual(n, 2)
832 self.assertEqual(bytes(b), b'Te')
833 self.assertFalse(resp.isclosed())
834 n = resp.readinto(b)
835 self.assertEqual(n, 2)
836 self.assertEqual(bytes(b), b'xt')
837 n = resp.readinto(b)
838 self.assertEqual(n, 0)
839 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200840 self.assertFalse(resp.closed)
841 resp.close()
842 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100843
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844 def test_host_port(self):
845 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000846
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200847 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000848 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000850 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
851 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000852 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200853 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000854 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200855 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
856 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000857 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000858 self.assertEqual(h, c.host)
859 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000860
Thomas Wouters89f507f2006-12-13 04:49:30 +0000861 def test_response_headers(self):
862 # test response with multiple message headers with the same field name.
863 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000864 'Set-Cookie: Customer="WILE_E_COYOTE"; '
865 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000866 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
867 ' Path="/acme"\r\n'
868 '\r\n'
869 'No body\r\n')
870 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
871 ', '
872 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
873 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000874 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000875 r.begin()
876 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000877 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000878
Thomas Wouters89f507f2006-12-13 04:49:30 +0000879 def test_read_head(self):
880 # Test that the library doesn't attempt to read any data
881 # from a HEAD request. (Tickles SF bug #622042.)
882 sock = FakeSocket(
883 'HTTP/1.1 200 OK\r\n'
884 'Content-Length: 14432\r\n'
885 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300886 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000887 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000888 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000889 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000891
Antoine Pitrou38d96432011-12-06 22:33:57 +0100892 def test_readinto_head(self):
893 # Test that the library doesn't attempt to read any data
894 # from a HEAD request. (Tickles SF bug #622042.)
895 sock = FakeSocket(
896 'HTTP/1.1 200 OK\r\n'
897 'Content-Length: 14432\r\n'
898 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300899 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100900 resp = client.HTTPResponse(sock, method="HEAD")
901 resp.begin()
902 b = bytearray(5)
903 if resp.readinto(b) != 0:
904 self.fail("Did not expect response from HEAD request")
905 self.assertEqual(bytes(b), b'\x00'*5)
906
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100907 def test_too_many_headers(self):
908 headers = '\r\n'.join('Header%d: foo' % i
909 for i in range(client._MAXHEADERS + 1)) + '\r\n'
910 text = ('HTTP/1.1 200 OK\r\n' + headers)
911 s = FakeSocket(text)
912 r = client.HTTPResponse(s)
913 self.assertRaisesRegex(client.HTTPException,
914 r"got more than \d+ headers", r.begin)
915
Thomas Wouters89f507f2006-12-13 04:49:30 +0000916 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000917 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000918 b'Accept-Encoding: identity\r\n'
919 b'Transfer-Encoding: chunked\r\n'
920 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921
Brett Cannon77b7de62010-10-29 23:31:11 +0000922 with open(__file__, 'rb') as body:
923 conn = client.HTTPConnection('example.com')
924 sock = FakeSocket(body)
925 conn.sock = sock
926 conn.request('GET', '/foo', body)
927 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
928 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000929
Antoine Pitrouead1d622009-09-29 18:44:53 +0000930 def test_send(self):
931 expected = b'this is a test this is only a test'
932 conn = client.HTTPConnection('example.com')
933 sock = FakeSocket(None)
934 conn.sock = sock
935 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000936 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000937 sock.data = b''
938 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000939 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000940 sock.data = b''
941 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000942 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000943
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300944 def test_send_updating_file(self):
945 def data():
946 yield 'data'
947 yield None
948 yield 'data_two'
949
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000950 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300951 mode = 'r'
952 d = data()
953 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000954 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300955
956 expected = b'data'
957
958 conn = client.HTTPConnection('example.com')
959 sock = FakeSocket("")
960 conn.sock = sock
961 conn.send(UpdatingFile())
962 self.assertEqual(sock.data, expected)
963
964
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000965 def test_send_iter(self):
966 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
967 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
968 b'\r\nonetwothree'
969
970 def body():
971 yield b"one"
972 yield b"two"
973 yield b"three"
974
975 conn = client.HTTPConnection('example.com')
976 sock = FakeSocket("")
977 conn.sock = sock
978 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000979 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000980
Nir Sofferad455cd2017-11-06 23:16:37 +0200981 def test_blocksize_request(self):
982 """Check that request() respects the configured block size."""
983 blocksize = 8 # For easy debugging.
984 conn = client.HTTPConnection('example.com', blocksize=blocksize)
985 sock = FakeSocket(None)
986 conn.sock = sock
987 expected = b"a" * blocksize + b"b"
988 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
989 self.assertEqual(sock.sendall_calls, 3)
990 body = sock.data.split(b"\r\n\r\n", 1)[1]
991 self.assertEqual(body, expected)
992
993 def test_blocksize_send(self):
994 """Check that send() respects the configured block size."""
995 blocksize = 8 # For easy debugging.
996 conn = client.HTTPConnection('example.com', blocksize=blocksize)
997 sock = FakeSocket(None)
998 conn.sock = sock
999 expected = b"a" * blocksize + b"b"
1000 conn.send(io.BytesIO(expected))
1001 self.assertEqual(sock.sendall_calls, 2)
1002 self.assertEqual(sock.data, expected)
1003
Senthil Kumaraneb71ad42011-08-02 18:33:41 +08001004 def test_send_type_error(self):
1005 # See: Issue #12676
1006 conn = client.HTTPConnection('example.com')
1007 conn.sock = FakeSocket('')
1008 with self.assertRaises(TypeError):
1009 conn.request('POST', 'test', conn)
1010
Christian Heimesa612dc02008-02-24 13:08:18 +00001011 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001012 expected = chunked_expected
1013 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001014 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +00001015 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001016 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +00001017 resp.close()
1018
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001019 # Various read sizes
1020 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001021 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001022 resp = client.HTTPResponse(sock, method="GET")
1023 resp.begin()
1024 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
1025 resp.close()
1026
Christian Heimesa612dc02008-02-24 13:08:18 +00001027 for x in ('', 'foo\r\n'):
1028 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001029 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +00001030 resp.begin()
1031 try:
1032 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001033 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001034 self.assertEqual(i.partial, expected)
1035 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
1036 self.assertEqual(repr(i), expected_message)
1037 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +00001038 else:
1039 self.fail('IncompleteRead expected')
1040 finally:
1041 resp.close()
1042
Antoine Pitrou38d96432011-12-06 22:33:57 +01001043 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001044
1045 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001046 nexpected = len(expected)
1047 b = bytearray(128)
1048
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001049 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +01001050 resp = client.HTTPResponse(sock, method="GET")
1051 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +01001052 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001053 self.assertEqual(b[:nexpected], expected)
1054 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +01001055 resp.close()
1056
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001057 # Various read sizes
1058 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001059 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001060 resp = client.HTTPResponse(sock, method="GET")
1061 resp.begin()
1062 m = memoryview(b)
1063 i = resp.readinto(m[0:n])
1064 i += resp.readinto(m[i:n + i])
1065 i += resp.readinto(m[i:])
1066 self.assertEqual(b[:nexpected], expected)
1067 self.assertEqual(i, nexpected)
1068 resp.close()
1069
Antoine Pitrou38d96432011-12-06 22:33:57 +01001070 for x in ('', 'foo\r\n'):
1071 sock = FakeSocket(chunked_start + x)
1072 resp = client.HTTPResponse(sock, method="GET")
1073 resp.begin()
1074 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +01001075 n = resp.readinto(b)
1076 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +01001077 self.assertEqual(i.partial, expected)
1078 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
1079 self.assertEqual(repr(i), expected_message)
1080 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +01001081 else:
1082 self.fail('IncompleteRead expected')
1083 finally:
1084 resp.close()
1085
Senthil Kumaran71fb6c82010-04-28 17:39:48 +00001086 def test_chunked_head(self):
1087 chunked_start = (
1088 'HTTP/1.1 200 OK\r\n'
1089 'Transfer-Encoding: chunked\r\n\r\n'
1090 'a\r\n'
1091 'hello world\r\n'
1092 '1\r\n'
1093 'd\r\n'
1094 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001095 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +00001096 resp = client.HTTPResponse(sock, method="HEAD")
1097 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +00001098 self.assertEqual(resp.read(), b'')
1099 self.assertEqual(resp.status, 200)
1100 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +00001101 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001102 self.assertFalse(resp.closed)
1103 resp.close()
1104 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +00001105
Antoine Pitrou38d96432011-12-06 22:33:57 +01001106 def test_readinto_chunked_head(self):
1107 chunked_start = (
1108 'HTTP/1.1 200 OK\r\n'
1109 'Transfer-Encoding: chunked\r\n\r\n'
1110 'a\r\n'
1111 'hello world\r\n'
1112 '1\r\n'
1113 'd\r\n'
1114 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001115 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +01001116 resp = client.HTTPResponse(sock, method="HEAD")
1117 resp.begin()
1118 b = bytearray(5)
1119 n = resp.readinto(b)
1120 self.assertEqual(n, 0)
1121 self.assertEqual(bytes(b), b'\x00'*5)
1122 self.assertEqual(resp.status, 200)
1123 self.assertEqual(resp.reason, 'OK')
1124 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +02001125 self.assertFalse(resp.closed)
1126 resp.close()
1127 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +01001128
Christian Heimesa612dc02008-02-24 13:08:18 +00001129 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +00001130 sock = FakeSocket(
1131 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001132 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +00001133 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +00001134 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +01001135 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +00001136
Benjamin Peterson6accb982009-03-02 22:50:25 +00001137 def test_incomplete_read(self):
1138 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001139 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +00001140 resp.begin()
1141 try:
1142 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001143 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001144 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001145 self.assertEqual(repr(i),
1146 "IncompleteRead(7 bytes read, 3 more expected)")
1147 self.assertEqual(str(i),
1148 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +01001149 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +00001150 else:
1151 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001152
Jeremy Hylton636950f2009-03-28 04:34:21 +00001153 def test_epipe(self):
1154 sock = EPipeSocket(
1155 "HTTP/1.0 401 Authorization Required\r\n"
1156 "Content-type: text/html\r\n"
1157 "WWW-Authenticate: Basic realm=\"example\"\r\n",
1158 b"Content-Length")
1159 conn = client.HTTPConnection("example.com")
1160 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +02001161 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +00001162 lambda: conn.request("PUT", "/url", "body"))
1163 resp = conn.getresponse()
1164 self.assertEqual(401, resp.status)
1165 self.assertEqual("Basic realm=\"example\"",
1166 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +00001167
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001168 # Test lines overflowing the max line size (_MAXLINE in http.client)
1169
1170 def test_overflowing_status_line(self):
1171 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1172 resp = client.HTTPResponse(FakeSocket(body))
1173 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1174
1175 def test_overflowing_header_line(self):
1176 body = (
1177 'HTTP/1.1 200 OK\r\n'
1178 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1179 )
1180 resp = client.HTTPResponse(FakeSocket(body))
1181 self.assertRaises(client.LineTooLong, resp.begin)
1182
Miss Islington (bot)60ba0b62021-05-05 16:14:28 -07001183 def test_overflowing_header_limit_after_100(self):
1184 body = (
1185 'HTTP/1.1 100 OK\r\n'
1186 'r\n' * 32768
1187 )
1188 resp = client.HTTPResponse(FakeSocket(body))
1189 self.assertRaises(client.HTTPException, resp.begin)
1190
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001191 def test_overflowing_chunked_line(self):
1192 body = (
1193 'HTTP/1.1 200 OK\r\n'
1194 'Transfer-Encoding: chunked\r\n\r\n'
1195 + '0' * 65536 + 'a\r\n'
1196 'hello world\r\n'
1197 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001198 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001199 )
1200 resp = client.HTTPResponse(FakeSocket(body))
1201 resp.begin()
1202 self.assertRaises(client.LineTooLong, resp.read)
1203
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001204 def test_early_eof(self):
1205 # Test httpresponse with no \r\n termination,
1206 body = "HTTP/1.1 200 Ok"
1207 sock = FakeSocket(body)
1208 resp = client.HTTPResponse(sock)
1209 resp.begin()
1210 self.assertEqual(resp.read(), b'')
1211 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001212 self.assertFalse(resp.closed)
1213 resp.close()
1214 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001215
Serhiy Storchakab491e052014-12-01 13:07:45 +02001216 def test_error_leak(self):
1217 # Test that the socket is not leaked if getresponse() fails
1218 conn = client.HTTPConnection('example.com')
1219 response = None
1220 class Response(client.HTTPResponse):
1221 def __init__(self, *pos, **kw):
1222 nonlocal response
1223 response = self # Avoid garbage collector closing the socket
1224 client.HTTPResponse.__init__(self, *pos, **kw)
1225 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001226 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001227 conn.request('GET', '/')
1228 self.assertRaises(client.BadStatusLine, conn.getresponse)
1229 self.assertTrue(response.closed)
1230 self.assertTrue(conn.sock.file_closed)
1231
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001232 def test_chunked_extension(self):
1233 extra = '3;foo=bar\r\n' + 'abc\r\n'
1234 expected = chunked_expected + b'abc'
1235
1236 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1237 resp = client.HTTPResponse(sock, method="GET")
1238 resp.begin()
1239 self.assertEqual(resp.read(), expected)
1240 resp.close()
1241
1242 def test_chunked_missing_end(self):
1243 """some servers may serve up a short chunked encoding stream"""
1244 expected = chunked_expected
1245 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1246 resp = client.HTTPResponse(sock, method="GET")
1247 resp.begin()
1248 self.assertEqual(resp.read(), expected)
1249 resp.close()
1250
1251 def test_chunked_trailers(self):
1252 """See that trailers are read and ignored"""
1253 expected = chunked_expected
1254 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1255 resp = client.HTTPResponse(sock, method="GET")
1256 resp.begin()
1257 self.assertEqual(resp.read(), expected)
1258 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001259 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001260 resp.close()
1261
1262 def test_chunked_sync(self):
1263 """Check that we don't read past the end of the chunked-encoding stream"""
1264 expected = chunked_expected
1265 extradata = "extradata"
1266 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1267 resp = client.HTTPResponse(sock, method="GET")
1268 resp.begin()
1269 self.assertEqual(resp.read(), expected)
1270 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001271 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001272 resp.close()
1273
1274 def test_content_length_sync(self):
1275 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001276 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001277 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001278 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001279 resp = client.HTTPResponse(sock, method="GET")
1280 resp.begin()
1281 self.assertEqual(resp.read(), expected)
1282 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001283 self.assertEqual(sock.file.read(), extradata) #we read to the end
1284 resp.close()
1285
1286 def test_readlines_content_length(self):
1287 extradata = b"extradata"
1288 expected = b"Hello123\r\n"
1289 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1290 resp = client.HTTPResponse(sock, method="GET")
1291 resp.begin()
1292 self.assertEqual(resp.readlines(2000), [expected])
1293 # the file should now have our extradata ready to be read
1294 self.assertEqual(sock.file.read(), extradata) #we read to the end
1295 resp.close()
1296
1297 def test_read1_content_length(self):
1298 extradata = b"extradata"
1299 expected = b"Hello123\r\n"
1300 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1301 resp = client.HTTPResponse(sock, method="GET")
1302 resp.begin()
1303 self.assertEqual(resp.read1(2000), expected)
1304 # the file should now have our extradata ready to be read
1305 self.assertEqual(sock.file.read(), extradata) #we read to the end
1306 resp.close()
1307
1308 def test_readline_bound_content_length(self):
1309 extradata = b"extradata"
1310 expected = b"Hello123\r\n"
1311 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1312 resp = client.HTTPResponse(sock, method="GET")
1313 resp.begin()
1314 self.assertEqual(resp.readline(10), expected)
1315 self.assertEqual(resp.readline(10), b"")
1316 # the file should now have our extradata ready to be read
1317 self.assertEqual(sock.file.read(), extradata) #we read to the end
1318 resp.close()
1319
1320 def test_read1_bound_content_length(self):
1321 extradata = b"extradata"
1322 expected = b"Hello123\r\n"
1323 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1324 resp = client.HTTPResponse(sock, method="GET")
1325 resp.begin()
1326 self.assertEqual(resp.read1(20), expected*2)
1327 self.assertEqual(resp.read(), expected)
1328 # the file should now have our extradata ready to be read
1329 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001330 resp.close()
1331
Martin Panterd979b2c2016-04-09 14:03:17 +00001332 def test_response_fileno(self):
1333 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001334 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001335 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001336
1337 result = None
1338 def run_server():
1339 [conn, address] = serv.accept()
1340 with conn, conn.makefile("rb") as reader:
1341 # Read the request header until a blank line
1342 while True:
1343 line = reader.readline()
1344 if not line.rstrip(b"\r\n"):
1345 break
1346 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1347 nonlocal result
1348 result = reader.read()
1349
1350 thread = threading.Thread(target=run_server)
1351 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001352 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001353 conn = client.HTTPConnection(*serv.getsockname())
1354 conn.request("CONNECT", "dummy:1234")
1355 response = conn.getresponse()
1356 try:
1357 self.assertEqual(response.status, client.OK)
1358 s = socket.socket(fileno=response.fileno())
1359 try:
1360 s.sendall(b"proxied data\n")
1361 finally:
1362 s.detach()
1363 finally:
1364 response.close()
1365 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001366 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001367 self.assertEqual(result, b"proxied data\n")
1368
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001369 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001370 """
1371 It should be possible to override the default validation
1372 behavior in putrequest (bpo-38216).
1373 """
1374 class UnsafeHTTPConnection(client.HTTPConnection):
1375 def _validate_path(self, url):
1376 pass
1377
1378 conn = UnsafeHTTPConnection('example.com')
1379 conn.sock = FakeSocket('')
1380 conn.putrequest('GET', '/\x00')
1381
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001382 def test_putrequest_override_host_validation(self):
1383 class UnsafeHTTPConnection(client.HTTPConnection):
1384 def _validate_host(self, url):
1385 pass
1386
1387 conn = UnsafeHTTPConnection('example.com\r\n')
1388 conn.sock = FakeSocket('')
1389 # set skip_host so a ValueError is not raised upon adding the
1390 # invalid URL as the value of the "Host:" header
1391 conn.putrequest('GET', '/', skip_host=1)
1392
Jason R. Coombs7774d782019-09-28 08:32:01 -04001393 def test_putrequest_override_encoding(self):
1394 """
1395 It should be possible to override the default encoding
1396 to transmit bytes in another encoding even if invalid
1397 (bpo-36274).
1398 """
1399 class UnsafeHTTPConnection(client.HTTPConnection):
1400 def _encode_request(self, str_url):
1401 return str_url.encode('utf-8')
1402
1403 conn = UnsafeHTTPConnection('example.com')
1404 conn.sock = FakeSocket('')
1405 conn.putrequest('GET', '/☃')
1406
1407
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001408class ExtendedReadTest(TestCase):
1409 """
1410 Test peek(), read1(), readline()
1411 """
1412 lines = (
1413 'HTTP/1.1 200 OK\r\n'
1414 '\r\n'
1415 'hello world!\n'
1416 'and now \n'
1417 'for something completely different\n'
1418 'foo'
1419 )
1420 lines_expected = lines[lines.find('hello'):].encode("ascii")
1421 lines_chunked = (
1422 'HTTP/1.1 200 OK\r\n'
1423 'Transfer-Encoding: chunked\r\n\r\n'
1424 'a\r\n'
1425 'hello worl\r\n'
1426 '3\r\n'
1427 'd!\n\r\n'
1428 '9\r\n'
1429 'and now \n\r\n'
1430 '23\r\n'
1431 'for something completely different\n\r\n'
1432 '3\r\n'
1433 'foo\r\n'
1434 '0\r\n' # terminating chunk
1435 '\r\n' # end of trailers
1436 )
1437
1438 def setUp(self):
1439 sock = FakeSocket(self.lines)
1440 resp = client.HTTPResponse(sock, method="GET")
1441 resp.begin()
1442 resp.fp = io.BufferedReader(resp.fp)
1443 self.resp = resp
1444
1445
1446
1447 def test_peek(self):
1448 resp = self.resp
1449 # patch up the buffered peek so that it returns not too much stuff
1450 oldpeek = resp.fp.peek
1451 def mypeek(n=-1):
1452 p = oldpeek(n)
1453 if n >= 0:
1454 return p[:n]
1455 return p[:10]
1456 resp.fp.peek = mypeek
1457
1458 all = []
1459 while True:
1460 # try a short peek
1461 p = resp.peek(3)
1462 if p:
1463 self.assertGreater(len(p), 0)
1464 # then unbounded peek
1465 p2 = resp.peek()
1466 self.assertGreaterEqual(len(p2), len(p))
1467 self.assertTrue(p2.startswith(p))
1468 next = resp.read(len(p2))
1469 self.assertEqual(next, p2)
1470 else:
1471 next = resp.read()
1472 self.assertFalse(next)
1473 all.append(next)
1474 if not next:
1475 break
1476 self.assertEqual(b"".join(all), self.lines_expected)
1477
1478 def test_readline(self):
1479 resp = self.resp
1480 self._verify_readline(self.resp.readline, self.lines_expected)
1481
1482 def _verify_readline(self, readline, expected):
1483 all = []
1484 while True:
1485 # short readlines
1486 line = readline(5)
1487 if line and line != b"foo":
1488 if len(line) < 5:
1489 self.assertTrue(line.endswith(b"\n"))
1490 all.append(line)
1491 if not line:
1492 break
1493 self.assertEqual(b"".join(all), expected)
1494
1495 def test_read1(self):
1496 resp = self.resp
1497 def r():
1498 res = resp.read1(4)
1499 self.assertLessEqual(len(res), 4)
1500 return res
1501 readliner = Readliner(r)
1502 self._verify_readline(readliner.readline, self.lines_expected)
1503
1504 def test_read1_unbounded(self):
1505 resp = self.resp
1506 all = []
1507 while True:
1508 data = resp.read1()
1509 if not data:
1510 break
1511 all.append(data)
1512 self.assertEqual(b"".join(all), self.lines_expected)
1513
1514 def test_read1_bounded(self):
1515 resp = self.resp
1516 all = []
1517 while True:
1518 data = resp.read1(10)
1519 if not data:
1520 break
1521 self.assertLessEqual(len(data), 10)
1522 all.append(data)
1523 self.assertEqual(b"".join(all), self.lines_expected)
1524
1525 def test_read1_0(self):
1526 self.assertEqual(self.resp.read1(0), b"")
1527
1528 def test_peek_0(self):
1529 p = self.resp.peek(0)
1530 self.assertLessEqual(0, len(p))
1531
Jason R. Coombs7774d782019-09-28 08:32:01 -04001532
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001533class ExtendedReadTestChunked(ExtendedReadTest):
1534 """
1535 Test peek(), read1(), readline() in chunked mode
1536 """
1537 lines = (
1538 'HTTP/1.1 200 OK\r\n'
1539 'Transfer-Encoding: chunked\r\n\r\n'
1540 'a\r\n'
1541 'hello worl\r\n'
1542 '3\r\n'
1543 'd!\n\r\n'
1544 '9\r\n'
1545 'and now \n\r\n'
1546 '23\r\n'
1547 'for something completely different\n\r\n'
1548 '3\r\n'
1549 'foo\r\n'
1550 '0\r\n' # terminating chunk
1551 '\r\n' # end of trailers
1552 )
1553
1554
1555class Readliner:
1556 """
1557 a simple readline class that uses an arbitrary read function and buffering
1558 """
1559 def __init__(self, readfunc):
1560 self.readfunc = readfunc
1561 self.remainder = b""
1562
1563 def readline(self, limit):
1564 data = []
1565 datalen = 0
1566 read = self.remainder
1567 try:
1568 while True:
1569 idx = read.find(b'\n')
1570 if idx != -1:
1571 break
1572 if datalen + len(read) >= limit:
1573 idx = limit - datalen - 1
1574 # read more data
1575 data.append(read)
1576 read = self.readfunc()
1577 if not read:
1578 idx = 0 #eof condition
1579 break
1580 idx += 1
1581 data.append(read[:idx])
1582 self.remainder = read[idx:]
1583 return b"".join(data)
1584 except:
1585 self.remainder = b"".join(data)
1586 raise
1587
Berker Peksagbabc6882015-02-20 09:39:38 +02001588
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001589class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001590 def test_all(self):
1591 # Documented objects defined in the module should be in __all__
Miss Islington (bot)60ba0b62021-05-05 16:14:28 -07001592 expected = {"responses"} # Allowlist documented dict() object
Berker Peksagbabc6882015-02-20 09:39:38 +02001593 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1594 # intentionally omitted for simplicity
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001595 denylist = {"HTTPMessage", "parse_headers"}
Berker Peksagbabc6882015-02-20 09:39:38 +02001596 for name in dir(client):
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001597 if name.startswith("_") or name in denylist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001598 continue
1599 module_object = getattr(client, name)
1600 if getattr(module_object, "__module__", None) == "http.client":
1601 expected.add(name)
1602 self.assertCountEqual(client.__all__, expected)
1603
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001604 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001605 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001606
Berker Peksagabbf0f42015-02-20 14:57:31 +02001607 def test_client_constants(self):
1608 # Make sure we don't break backward compatibility with 3.4
1609 expected = [
1610 'CONTINUE',
1611 'SWITCHING_PROTOCOLS',
1612 'PROCESSING',
1613 'OK',
1614 'CREATED',
1615 'ACCEPTED',
1616 'NON_AUTHORITATIVE_INFORMATION',
1617 'NO_CONTENT',
1618 'RESET_CONTENT',
1619 'PARTIAL_CONTENT',
1620 'MULTI_STATUS',
1621 'IM_USED',
1622 'MULTIPLE_CHOICES',
1623 'MOVED_PERMANENTLY',
1624 'FOUND',
1625 'SEE_OTHER',
1626 'NOT_MODIFIED',
1627 'USE_PROXY',
1628 'TEMPORARY_REDIRECT',
1629 'BAD_REQUEST',
1630 'UNAUTHORIZED',
1631 'PAYMENT_REQUIRED',
1632 'FORBIDDEN',
1633 'NOT_FOUND',
1634 'METHOD_NOT_ALLOWED',
1635 'NOT_ACCEPTABLE',
1636 'PROXY_AUTHENTICATION_REQUIRED',
1637 'REQUEST_TIMEOUT',
1638 'CONFLICT',
1639 'GONE',
1640 'LENGTH_REQUIRED',
1641 'PRECONDITION_FAILED',
1642 'REQUEST_ENTITY_TOO_LARGE',
1643 'REQUEST_URI_TOO_LONG',
1644 'UNSUPPORTED_MEDIA_TYPE',
1645 'REQUESTED_RANGE_NOT_SATISFIABLE',
1646 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001647 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001648 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001649 'UNPROCESSABLE_ENTITY',
1650 'LOCKED',
1651 'FAILED_DEPENDENCY',
1652 'UPGRADE_REQUIRED',
1653 'PRECONDITION_REQUIRED',
1654 'TOO_MANY_REQUESTS',
1655 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001656 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001657 'INTERNAL_SERVER_ERROR',
1658 'NOT_IMPLEMENTED',
1659 'BAD_GATEWAY',
1660 'SERVICE_UNAVAILABLE',
1661 'GATEWAY_TIMEOUT',
1662 'HTTP_VERSION_NOT_SUPPORTED',
1663 'INSUFFICIENT_STORAGE',
1664 'NOT_EXTENDED',
1665 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001666 'EARLY_HINTS',
1667 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001668 ]
1669 for const in expected:
1670 with self.subTest(constant=const):
1671 self.assertTrue(hasattr(client, const))
1672
Gregory P. Smithb4066372010-01-03 03:28:29 +00001673
1674class SourceAddressTest(TestCase):
1675 def setUp(self):
1676 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001677 self.port = socket_helper.bind_port(self.serv)
1678 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001679 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001680 self.conn = None
1681
1682 def tearDown(self):
1683 if self.conn:
1684 self.conn.close()
1685 self.conn = None
1686 self.serv.close()
1687 self.serv = None
1688
1689 def testHTTPConnectionSourceAddress(self):
1690 self.conn = client.HTTPConnection(HOST, self.port,
1691 source_address=('', self.source_port))
1692 self.conn.connect()
1693 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1694
1695 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1696 'http.client.HTTPSConnection not defined')
1697 def testHTTPSConnectionSourceAddress(self):
1698 self.conn = client.HTTPSConnection(HOST, self.port,
1699 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001700 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001701 # this code doesn't deal with setting up an active running SSL server
1702 # for an ssl_wrapped connect() to actually return from.
1703
1704
Guido van Rossumd8faa362007-04-27 19:54:29 +00001705class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001706 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001707
1708 def setUp(self):
1709 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001710 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001711 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001712
1713 def tearDown(self):
1714 self.serv.close()
1715 self.serv = None
1716
1717 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001718 # This will prove that the timeout gets through HTTPConnection
1719 # and into the socket.
1720
Georg Brandlf78e02b2008-06-10 17:40:04 +00001721 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001722 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001723 socket.setdefaulttimeout(30)
1724 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001725 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001726 httpConn.connect()
1727 finally:
1728 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729 self.assertEqual(httpConn.sock.gettimeout(), 30)
1730 httpConn.close()
1731
Georg Brandlf78e02b2008-06-10 17:40:04 +00001732 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001733 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734 socket.setdefaulttimeout(30)
1735 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001736 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001737 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001738 httpConn.connect()
1739 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001740 socket.setdefaulttimeout(None)
1741 self.assertEqual(httpConn.sock.gettimeout(), None)
1742 httpConn.close()
1743
1744 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001745 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001746 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001747 self.assertEqual(httpConn.sock.gettimeout(), 30)
1748 httpConn.close()
1749
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001750
R David Murraycae7bdb2015-04-05 19:26:29 -04001751class PersistenceTest(TestCase):
1752
1753 def test_reuse_reconnect(self):
1754 # Should reuse or reconnect depending on header from server
1755 tests = (
1756 ('1.0', '', False),
1757 ('1.0', 'Connection: keep-alive\r\n', True),
1758 ('1.1', '', True),
1759 ('1.1', 'Connection: close\r\n', False),
1760 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1761 ('1.1', 'Connection: cloSE\r\n', False),
1762 )
1763 for version, header, reuse in tests:
1764 with self.subTest(version=version, header=header):
1765 msg = (
1766 'HTTP/{} 200 OK\r\n'
1767 '{}'
1768 'Content-Length: 12\r\n'
1769 '\r\n'
1770 'Dummy body\r\n'
1771 ).format(version, header)
1772 conn = FakeSocketHTTPConnection(msg)
1773 self.assertIsNone(conn.sock)
1774 conn.request('GET', '/open-connection')
1775 with conn.getresponse() as response:
1776 self.assertEqual(conn.sock is None, not reuse)
1777 response.read()
1778 self.assertEqual(conn.sock is None, not reuse)
1779 self.assertEqual(conn.connections, 1)
1780 conn.request('GET', '/subsequent-request')
1781 self.assertEqual(conn.connections, 1 if reuse else 2)
1782
1783 def test_disconnected(self):
1784
1785 def make_reset_reader(text):
1786 """Return BufferedReader that raises ECONNRESET at EOF"""
1787 stream = io.BytesIO(text)
1788 def readinto(buffer):
1789 size = io.BytesIO.readinto(stream, buffer)
1790 if size == 0:
1791 raise ConnectionResetError()
1792 return size
1793 stream.readinto = readinto
1794 return io.BufferedReader(stream)
1795
1796 tests = (
1797 (io.BytesIO, client.RemoteDisconnected),
1798 (make_reset_reader, ConnectionResetError),
1799 )
1800 for stream_factory, exception in tests:
1801 with self.subTest(exception=exception):
1802 conn = FakeSocketHTTPConnection(b'', stream_factory)
1803 conn.request('GET', '/eof-response')
1804 self.assertRaises(exception, conn.getresponse)
1805 self.assertIsNone(conn.sock)
1806 # HTTPConnection.connect() should be automatically invoked
1807 conn.request('GET', '/reconnect')
1808 self.assertEqual(conn.connections, 2)
1809
1810 def test_100_close(self):
1811 conn = FakeSocketHTTPConnection(
1812 b'HTTP/1.1 100 Continue\r\n'
1813 b'\r\n'
1814 # Missing final response
1815 )
1816 conn.request('GET', '/', headers={'Expect': '100-continue'})
1817 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1818 self.assertIsNone(conn.sock)
1819 conn.request('GET', '/reconnect')
1820 self.assertEqual(conn.connections, 2)
1821
1822
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001823class HTTPSTest(TestCase):
1824
1825 def setUp(self):
1826 if not hasattr(client, 'HTTPSConnection'):
1827 self.skipTest('ssl support required')
1828
1829 def make_server(self, certfile):
1830 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001831 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001832
1833 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001834 # simple test to check it's storing the timeout
1835 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1836 self.assertEqual(h.timeout, 30)
1837
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001838 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001839 # Default settings: requires a valid cert from a trusted CA
1840 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001841 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001842 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001843 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1844 with self.assertRaises(ssl.SSLError) as exc_info:
1845 h.request('GET', '/')
1846 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1847
1848 def test_networked_noverification(self):
1849 # Switch off cert verification
1850 import ssl
1851 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001852 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001853 context = ssl._create_unverified_context()
1854 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1855 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001856 h.request('GET', '/')
1857 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001858 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001859 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001860 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001861
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001862 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001863 def test_networked_trusted_by_default_cert(self):
1864 # Default settings: requires a valid cert from a trusted CA
1865 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001866 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001867 h = client.HTTPSConnection('www.python.org', 443)
1868 h.request('GET', '/')
1869 resp = h.getresponse()
1870 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001871 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001872 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001873 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001874
1875 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001876 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001877 import ssl
1878 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001879 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001880 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001881 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1882 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1883 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001884 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001885 try:
1886 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1887 context=context)
1888 h.request('GET', '/')
1889 resp = h.getresponse()
1890 except ssl.SSLError as ssl_err:
1891 ssl_err_str = str(ssl_err)
1892 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1893 # modern Linux distros (Debian Buster, etc) default OpenSSL
1894 # configurations it'll fail saying "key too weak" until we
1895 # address https://bugs.python.org/issue36816 to use a proper
1896 # key size on self-signed.pythontest.net.
1897 if re.search(r'(?i)key.too.weak', ssl_err_str):
1898 raise unittest.SkipTest(
1899 f'Got {ssl_err_str} trying to connect '
1900 f'to {selfsigned_pythontestdotnet}. '
1901 'See https://bugs.python.org/issue36816.')
1902 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001903 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001904 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001905 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001906 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001907
1908 def test_networked_bad_cert(self):
1909 # We feed a "CA" cert that is unrelated to the server's cert
1910 import ssl
1911 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001912 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001913 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001914 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001915 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1916 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001917 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001918 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1919
1920 def test_local_unknown_cert(self):
1921 # The custom cert isn't known to the default trust bundle
1922 import ssl
1923 server = self.make_server(CERT_localhost)
1924 h = client.HTTPSConnection('localhost', server.port)
1925 with self.assertRaises(ssl.SSLError) as exc_info:
1926 h.request('GET', '/')
1927 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001928
1929 def test_local_good_hostname(self):
1930 # The (valid) cert validates the HTTP hostname
1931 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001932 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001933 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001934 context.load_verify_locations(CERT_localhost)
1935 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001936 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001937 h.request('GET', '/nonexistent')
1938 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001939 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001940 self.assertEqual(resp.status, 404)
1941
1942 def test_local_bad_hostname(self):
1943 # The (valid) cert doesn't validate the HTTP hostname
1944 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001945 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001946 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001947 context.load_verify_locations(CERT_fakehostname)
1948 h = client.HTTPSConnection('localhost', server.port, context=context)
1949 with self.assertRaises(ssl.CertificateError):
1950 h.request('GET', '/')
1951 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001952 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001953 h = client.HTTPSConnection('localhost', server.port,
1954 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001955 with self.assertRaises(ssl.CertificateError):
1956 h.request('GET', '/')
1957 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001958 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001959 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001960 h = client.HTTPSConnection('localhost', server.port,
1961 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001962 h.request('GET', '/nonexistent')
1963 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001964 resp.close()
1965 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001966 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001967 # The context's check_hostname setting is used if one isn't passed to
1968 # HTTPSConnection.
1969 context.check_hostname = False
1970 h = client.HTTPSConnection('localhost', server.port, context=context)
1971 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001972 resp = h.getresponse()
1973 self.assertEqual(resp.status, 404)
1974 resp.close()
1975 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001976 # Passing check_hostname to HTTPSConnection should override the
1977 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001978 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001979 h = client.HTTPSConnection('localhost', server.port,
1980 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001981 with self.assertRaises(ssl.CertificateError):
1982 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001983
Petri Lehtinene119c402011-10-26 21:29:15 +03001984 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1985 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001986 def test_host_port(self):
1987 # Check invalid host_port
1988
1989 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1990 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1991
1992 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1993 "fe80::207:e9ff:fe9b", 8000),
1994 ("www.python.org:443", "www.python.org", 443),
1995 ("www.python.org:", "www.python.org", 443),
1996 ("www.python.org", "www.python.org", 443),
1997 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1998 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1999 443)):
2000 c = client.HTTPSConnection(hp)
2001 self.assertEqual(h, c.host)
2002 self.assertEqual(p, c.port)
2003
Christian Heimesd1bd6e72019-07-01 08:32:24 +02002004 def test_tls13_pha(self):
2005 import ssl
2006 if not ssl.HAS_TLSv1_3:
2007 self.skipTest('TLS 1.3 support required')
2008 # just check status of PHA flag
2009 h = client.HTTPSConnection('localhost', 443)
2010 self.assertTrue(h._context.post_handshake_auth)
2011
2012 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2013 self.assertFalse(context.post_handshake_auth)
2014 h = client.HTTPSConnection('localhost', 443, context=context)
2015 self.assertIs(h._context, context)
2016 self.assertFalse(h._context.post_handshake_auth)
2017
Pablo Galindoaa542c22019-08-08 23:25:46 +01002018 with warnings.catch_warnings():
2019 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
2020 DeprecationWarning)
2021 h = client.HTTPSConnection('localhost', 443, context=context,
2022 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02002023 self.assertTrue(h._context.post_handshake_auth)
2024
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002025
Jeremy Hylton236654b2009-03-27 20:24:34 +00002026class RequestBodyTest(TestCase):
2027 """Test cases where a request includes a message body."""
2028
2029 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002030 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00002031 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00002032 self.conn.sock = self.sock
2033
2034 def get_headers_and_fp(self):
2035 f = io.BytesIO(self.sock.data)
2036 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002037 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00002038 return message, f
2039
Martin Panter3c0d0ba2016-08-24 06:33:33 +00002040 def test_list_body(self):
2041 # Note that no content-length is automatically calculated for
2042 # an iterable. The request will fall back to send chunked
2043 # transfer encoding.
2044 cases = (
2045 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2046 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2047 )
2048 for body, expected in cases:
2049 with self.subTest(body):
2050 self.conn = client.HTTPConnection('example.com')
2051 self.conn.sock = self.sock = FakeSocket('')
2052
2053 self.conn.request('PUT', '/url', body)
2054 msg, f = self.get_headers_and_fp()
2055 self.assertNotIn('Content-Type', msg)
2056 self.assertNotIn('Content-Length', msg)
2057 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
2058 self.assertEqual(expected, f.read())
2059
Jeremy Hylton236654b2009-03-27 20:24:34 +00002060 def test_manual_content_length(self):
2061 # Set an incorrect content-length so that we can verify that
2062 # it will not be over-ridden by the library.
2063 self.conn.request("PUT", "/url", "body",
2064 {"Content-Length": "42"})
2065 message, f = self.get_headers_and_fp()
2066 self.assertEqual("42", message.get("content-length"))
2067 self.assertEqual(4, len(f.read()))
2068
2069 def test_ascii_body(self):
2070 self.conn.request("PUT", "/url", "body")
2071 message, f = self.get_headers_and_fp()
2072 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002073 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002074 self.assertEqual("4", message.get("content-length"))
2075 self.assertEqual(b'body', f.read())
2076
2077 def test_latin1_body(self):
2078 self.conn.request("PUT", "/url", "body\xc1")
2079 message, f = self.get_headers_and_fp()
2080 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002081 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002082 self.assertEqual("5", message.get("content-length"))
2083 self.assertEqual(b'body\xc1', f.read())
2084
2085 def test_bytes_body(self):
2086 self.conn.request("PUT", "/url", b"body\xc1")
2087 message, f = self.get_headers_and_fp()
2088 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002089 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002090 self.assertEqual("5", message.get("content-length"))
2091 self.assertEqual(b'body\xc1', f.read())
2092
Martin Panteref91bb22016-08-27 01:39:26 +00002093 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08002094 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
Inada Naokifa51c0c2021-04-29 11:34:56 +09002095 with open(os_helper.TESTFN, "w", encoding="utf-8") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002096 f.write("body")
Inada Naokifa51c0c2021-04-29 11:34:56 +09002097 with open(os_helper.TESTFN, encoding="utf-8") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002098 self.conn.request("PUT", "/url", f)
2099 message, f = self.get_headers_and_fp()
2100 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002101 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00002102 # No content-length will be determined for files; the body
2103 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00002104 self.assertIsNone(message.get("content-length"))
2105 self.assertEqual("chunked", message.get("transfer-encoding"))
2106 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002107
2108 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08002109 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2110 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002111 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08002112 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002113 self.conn.request("PUT", "/url", f)
2114 message, f = self.get_headers_and_fp()
2115 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002116 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00002117 self.assertEqual("chunked", message.get("Transfer-Encoding"))
2118 self.assertNotIn("Content-Length", message)
2119 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002120
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00002121
2122class HTTPResponseTest(TestCase):
2123
2124 def setUp(self):
2125 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
2126 second-value\r\n\r\nText"
2127 sock = FakeSocket(body)
2128 self.resp = client.HTTPResponse(sock)
2129 self.resp.begin()
2130
2131 def test_getting_header(self):
2132 header = self.resp.getheader('My-Header')
2133 self.assertEqual(header, 'first-value, second-value')
2134
2135 header = self.resp.getheader('My-Header', 'some default')
2136 self.assertEqual(header, 'first-value, second-value')
2137
2138 def test_getting_nonexistent_header_with_string_default(self):
2139 header = self.resp.getheader('No-Such-Header', 'default-value')
2140 self.assertEqual(header, 'default-value')
2141
2142 def test_getting_nonexistent_header_with_iterable_default(self):
2143 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
2144 self.assertEqual(header, 'default, values')
2145
2146 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
2147 self.assertEqual(header, 'default, values')
2148
2149 def test_getting_nonexistent_header_without_default(self):
2150 header = self.resp.getheader('No-Such-Header')
2151 self.assertEqual(header, None)
2152
2153 def test_getting_header_defaultint(self):
2154 header = self.resp.getheader('No-Such-Header',default=42)
2155 self.assertEqual(header, 42)
2156
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002157class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002158 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002159 response_text = (
2160 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
2161 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2162 'Content-Length: 42\r\n\r\n'
2163 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002164 self.host = 'proxy.com'
2165 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02002166 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002167
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002168 def tearDown(self):
2169 self.conn.close()
2170
Berker Peksagab53ab02015-02-03 12:22:11 +02002171 def _create_connection(self, response_text):
2172 def create_connection(address, timeout=None, source_address=None):
2173 return FakeSocket(response_text, host=address[0], port=address[1])
2174 return create_connection
2175
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002176 def test_set_tunnel_host_port_headers(self):
2177 tunnel_host = 'destination.com'
2178 tunnel_port = 8888
2179 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2180 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2181 headers=tunnel_headers)
2182 self.conn.request('HEAD', '/', '')
2183 self.assertEqual(self.conn.sock.host, self.host)
2184 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2185 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2186 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2187 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2188
2189 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002190 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002191 self.conn.connect()
2192 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002193 'destination.com')
2194
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002195 def test_connect_with_tunnel(self):
2196 self.conn.set_tunnel('destination.com')
2197 self.conn.request('HEAD', '/', '')
2198 self.assertEqual(self.conn.sock.host, self.host)
2199 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2200 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002201 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002202 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2203 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002204
2205 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002206 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002207
Gregory P. Smithc25910a2021-03-07 23:35:13 -08002208 def test_tunnel_connect_single_send_connection_setup(self):
2209 """Regresstion test for https://bugs.python.org/issue43332."""
2210 with mock.patch.object(self.conn, 'send') as mock_send:
2211 self.conn.set_tunnel('destination.com')
2212 self.conn.connect()
2213 self.conn.request('GET', '/')
2214 mock_send.assert_called()
2215 # Likely 2, but this test only cares about the first.
2216 self.assertGreater(
2217 len(mock_send.mock_calls), 1,
2218 msg=f'unexpected number of send calls: {mock_send.mock_calls}')
2219 proxy_setup_data_sent = mock_send.mock_calls[0][1][0]
2220 self.assertIn(b'CONNECT destination.com', proxy_setup_data_sent)
2221 self.assertTrue(
2222 proxy_setup_data_sent.endswith(b'\r\n\r\n'),
2223 msg=f'unexpected proxy data sent {proxy_setup_data_sent!r}')
2224
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002225 def test_connect_put_request(self):
2226 self.conn.set_tunnel('destination.com')
2227 self.conn.request('PUT', '/', '')
2228 self.assertEqual(self.conn.sock.host, self.host)
2229 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2230 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2231 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2232
Berker Peksagab53ab02015-02-03 12:22:11 +02002233 def test_tunnel_debuglog(self):
2234 expected_header = 'X-Dummy: 1'
2235 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2236
2237 self.conn.set_debuglevel(1)
2238 self.conn._create_connection = self._create_connection(response_text)
2239 self.conn.set_tunnel('destination.com')
2240
2241 with support.captured_stdout() as output:
2242 self.conn.request('PUT', '/', '')
2243 lines = output.getvalue().splitlines()
2244 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002245
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002246
Thomas Wouters89f507f2006-12-13 04:49:30 +00002247if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002248 unittest.main(verbosity=2)