blob: db41e29a4b839402c0a562eb950588e7bc866065 [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
1183 def test_overflowing_chunked_line(self):
1184 body = (
1185 'HTTP/1.1 200 OK\r\n'
1186 'Transfer-Encoding: chunked\r\n\r\n'
1187 + '0' * 65536 + 'a\r\n'
1188 'hello world\r\n'
1189 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001190 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001191 )
1192 resp = client.HTTPResponse(FakeSocket(body))
1193 resp.begin()
1194 self.assertRaises(client.LineTooLong, resp.read)
1195
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001196 def test_early_eof(self):
1197 # Test httpresponse with no \r\n termination,
1198 body = "HTTP/1.1 200 Ok"
1199 sock = FakeSocket(body)
1200 resp = client.HTTPResponse(sock)
1201 resp.begin()
1202 self.assertEqual(resp.read(), b'')
1203 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001204 self.assertFalse(resp.closed)
1205 resp.close()
1206 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001207
Serhiy Storchakab491e052014-12-01 13:07:45 +02001208 def test_error_leak(self):
1209 # Test that the socket is not leaked if getresponse() fails
1210 conn = client.HTTPConnection('example.com')
1211 response = None
1212 class Response(client.HTTPResponse):
1213 def __init__(self, *pos, **kw):
1214 nonlocal response
1215 response = self # Avoid garbage collector closing the socket
1216 client.HTTPResponse.__init__(self, *pos, **kw)
1217 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001218 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001219 conn.request('GET', '/')
1220 self.assertRaises(client.BadStatusLine, conn.getresponse)
1221 self.assertTrue(response.closed)
1222 self.assertTrue(conn.sock.file_closed)
1223
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001224 def test_chunked_extension(self):
1225 extra = '3;foo=bar\r\n' + 'abc\r\n'
1226 expected = chunked_expected + b'abc'
1227
1228 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1229 resp = client.HTTPResponse(sock, method="GET")
1230 resp.begin()
1231 self.assertEqual(resp.read(), expected)
1232 resp.close()
1233
1234 def test_chunked_missing_end(self):
1235 """some servers may serve up a short chunked encoding stream"""
1236 expected = chunked_expected
1237 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1238 resp = client.HTTPResponse(sock, method="GET")
1239 resp.begin()
1240 self.assertEqual(resp.read(), expected)
1241 resp.close()
1242
1243 def test_chunked_trailers(self):
1244 """See that trailers are read and ignored"""
1245 expected = chunked_expected
1246 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1247 resp = client.HTTPResponse(sock, method="GET")
1248 resp.begin()
1249 self.assertEqual(resp.read(), expected)
1250 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001251 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001252 resp.close()
1253
1254 def test_chunked_sync(self):
1255 """Check that we don't read past the end of the chunked-encoding stream"""
1256 expected = chunked_expected
1257 extradata = "extradata"
1258 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1259 resp = client.HTTPResponse(sock, method="GET")
1260 resp.begin()
1261 self.assertEqual(resp.read(), expected)
1262 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001263 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001264 resp.close()
1265
1266 def test_content_length_sync(self):
1267 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001268 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001269 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001270 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 +00001271 resp = client.HTTPResponse(sock, method="GET")
1272 resp.begin()
1273 self.assertEqual(resp.read(), expected)
1274 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001275 self.assertEqual(sock.file.read(), extradata) #we read to the end
1276 resp.close()
1277
1278 def test_readlines_content_length(self):
1279 extradata = b"extradata"
1280 expected = b"Hello123\r\n"
1281 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1282 resp = client.HTTPResponse(sock, method="GET")
1283 resp.begin()
1284 self.assertEqual(resp.readlines(2000), [expected])
1285 # the file should now have our extradata ready to be read
1286 self.assertEqual(sock.file.read(), extradata) #we read to the end
1287 resp.close()
1288
1289 def test_read1_content_length(self):
1290 extradata = b"extradata"
1291 expected = b"Hello123\r\n"
1292 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1293 resp = client.HTTPResponse(sock, method="GET")
1294 resp.begin()
1295 self.assertEqual(resp.read1(2000), expected)
1296 # the file should now have our extradata ready to be read
1297 self.assertEqual(sock.file.read(), extradata) #we read to the end
1298 resp.close()
1299
1300 def test_readline_bound_content_length(self):
1301 extradata = b"extradata"
1302 expected = b"Hello123\r\n"
1303 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1304 resp = client.HTTPResponse(sock, method="GET")
1305 resp.begin()
1306 self.assertEqual(resp.readline(10), expected)
1307 self.assertEqual(resp.readline(10), b"")
1308 # the file should now have our extradata ready to be read
1309 self.assertEqual(sock.file.read(), extradata) #we read to the end
1310 resp.close()
1311
1312 def test_read1_bound_content_length(self):
1313 extradata = b"extradata"
1314 expected = b"Hello123\r\n"
1315 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1316 resp = client.HTTPResponse(sock, method="GET")
1317 resp.begin()
1318 self.assertEqual(resp.read1(20), expected*2)
1319 self.assertEqual(resp.read(), expected)
1320 # the file should now have our extradata ready to be read
1321 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001322 resp.close()
1323
Martin Panterd979b2c2016-04-09 14:03:17 +00001324 def test_response_fileno(self):
1325 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001326 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001327 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001328
1329 result = None
1330 def run_server():
1331 [conn, address] = serv.accept()
1332 with conn, conn.makefile("rb") as reader:
1333 # Read the request header until a blank line
1334 while True:
1335 line = reader.readline()
1336 if not line.rstrip(b"\r\n"):
1337 break
1338 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1339 nonlocal result
1340 result = reader.read()
1341
1342 thread = threading.Thread(target=run_server)
1343 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001344 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001345 conn = client.HTTPConnection(*serv.getsockname())
1346 conn.request("CONNECT", "dummy:1234")
1347 response = conn.getresponse()
1348 try:
1349 self.assertEqual(response.status, client.OK)
1350 s = socket.socket(fileno=response.fileno())
1351 try:
1352 s.sendall(b"proxied data\n")
1353 finally:
1354 s.detach()
1355 finally:
1356 response.close()
1357 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001358 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001359 self.assertEqual(result, b"proxied data\n")
1360
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001361 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001362 """
1363 It should be possible to override the default validation
1364 behavior in putrequest (bpo-38216).
1365 """
1366 class UnsafeHTTPConnection(client.HTTPConnection):
1367 def _validate_path(self, url):
1368 pass
1369
1370 conn = UnsafeHTTPConnection('example.com')
1371 conn.sock = FakeSocket('')
1372 conn.putrequest('GET', '/\x00')
1373
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001374 def test_putrequest_override_host_validation(self):
1375 class UnsafeHTTPConnection(client.HTTPConnection):
1376 def _validate_host(self, url):
1377 pass
1378
1379 conn = UnsafeHTTPConnection('example.com\r\n')
1380 conn.sock = FakeSocket('')
1381 # set skip_host so a ValueError is not raised upon adding the
1382 # invalid URL as the value of the "Host:" header
1383 conn.putrequest('GET', '/', skip_host=1)
1384
Jason R. Coombs7774d782019-09-28 08:32:01 -04001385 def test_putrequest_override_encoding(self):
1386 """
1387 It should be possible to override the default encoding
1388 to transmit bytes in another encoding even if invalid
1389 (bpo-36274).
1390 """
1391 class UnsafeHTTPConnection(client.HTTPConnection):
1392 def _encode_request(self, str_url):
1393 return str_url.encode('utf-8')
1394
1395 conn = UnsafeHTTPConnection('example.com')
1396 conn.sock = FakeSocket('')
1397 conn.putrequest('GET', '/☃')
1398
1399
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001400class ExtendedReadTest(TestCase):
1401 """
1402 Test peek(), read1(), readline()
1403 """
1404 lines = (
1405 'HTTP/1.1 200 OK\r\n'
1406 '\r\n'
1407 'hello world!\n'
1408 'and now \n'
1409 'for something completely different\n'
1410 'foo'
1411 )
1412 lines_expected = lines[lines.find('hello'):].encode("ascii")
1413 lines_chunked = (
1414 'HTTP/1.1 200 OK\r\n'
1415 'Transfer-Encoding: chunked\r\n\r\n'
1416 'a\r\n'
1417 'hello worl\r\n'
1418 '3\r\n'
1419 'd!\n\r\n'
1420 '9\r\n'
1421 'and now \n\r\n'
1422 '23\r\n'
1423 'for something completely different\n\r\n'
1424 '3\r\n'
1425 'foo\r\n'
1426 '0\r\n' # terminating chunk
1427 '\r\n' # end of trailers
1428 )
1429
1430 def setUp(self):
1431 sock = FakeSocket(self.lines)
1432 resp = client.HTTPResponse(sock, method="GET")
1433 resp.begin()
1434 resp.fp = io.BufferedReader(resp.fp)
1435 self.resp = resp
1436
1437
1438
1439 def test_peek(self):
1440 resp = self.resp
1441 # patch up the buffered peek so that it returns not too much stuff
1442 oldpeek = resp.fp.peek
1443 def mypeek(n=-1):
1444 p = oldpeek(n)
1445 if n >= 0:
1446 return p[:n]
1447 return p[:10]
1448 resp.fp.peek = mypeek
1449
1450 all = []
1451 while True:
1452 # try a short peek
1453 p = resp.peek(3)
1454 if p:
1455 self.assertGreater(len(p), 0)
1456 # then unbounded peek
1457 p2 = resp.peek()
1458 self.assertGreaterEqual(len(p2), len(p))
1459 self.assertTrue(p2.startswith(p))
1460 next = resp.read(len(p2))
1461 self.assertEqual(next, p2)
1462 else:
1463 next = resp.read()
1464 self.assertFalse(next)
1465 all.append(next)
1466 if not next:
1467 break
1468 self.assertEqual(b"".join(all), self.lines_expected)
1469
1470 def test_readline(self):
1471 resp = self.resp
1472 self._verify_readline(self.resp.readline, self.lines_expected)
1473
1474 def _verify_readline(self, readline, expected):
1475 all = []
1476 while True:
1477 # short readlines
1478 line = readline(5)
1479 if line and line != b"foo":
1480 if len(line) < 5:
1481 self.assertTrue(line.endswith(b"\n"))
1482 all.append(line)
1483 if not line:
1484 break
1485 self.assertEqual(b"".join(all), expected)
1486
1487 def test_read1(self):
1488 resp = self.resp
1489 def r():
1490 res = resp.read1(4)
1491 self.assertLessEqual(len(res), 4)
1492 return res
1493 readliner = Readliner(r)
1494 self._verify_readline(readliner.readline, self.lines_expected)
1495
1496 def test_read1_unbounded(self):
1497 resp = self.resp
1498 all = []
1499 while True:
1500 data = resp.read1()
1501 if not data:
1502 break
1503 all.append(data)
1504 self.assertEqual(b"".join(all), self.lines_expected)
1505
1506 def test_read1_bounded(self):
1507 resp = self.resp
1508 all = []
1509 while True:
1510 data = resp.read1(10)
1511 if not data:
1512 break
1513 self.assertLessEqual(len(data), 10)
1514 all.append(data)
1515 self.assertEqual(b"".join(all), self.lines_expected)
1516
1517 def test_read1_0(self):
1518 self.assertEqual(self.resp.read1(0), b"")
1519
1520 def test_peek_0(self):
1521 p = self.resp.peek(0)
1522 self.assertLessEqual(0, len(p))
1523
Jason R. Coombs7774d782019-09-28 08:32:01 -04001524
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001525class ExtendedReadTestChunked(ExtendedReadTest):
1526 """
1527 Test peek(), read1(), readline() in chunked mode
1528 """
1529 lines = (
1530 'HTTP/1.1 200 OK\r\n'
1531 'Transfer-Encoding: chunked\r\n\r\n'
1532 'a\r\n'
1533 'hello worl\r\n'
1534 '3\r\n'
1535 'd!\n\r\n'
1536 '9\r\n'
1537 'and now \n\r\n'
1538 '23\r\n'
1539 'for something completely different\n\r\n'
1540 '3\r\n'
1541 'foo\r\n'
1542 '0\r\n' # terminating chunk
1543 '\r\n' # end of trailers
1544 )
1545
1546
1547class Readliner:
1548 """
1549 a simple readline class that uses an arbitrary read function and buffering
1550 """
1551 def __init__(self, readfunc):
1552 self.readfunc = readfunc
1553 self.remainder = b""
1554
1555 def readline(self, limit):
1556 data = []
1557 datalen = 0
1558 read = self.remainder
1559 try:
1560 while True:
1561 idx = read.find(b'\n')
1562 if idx != -1:
1563 break
1564 if datalen + len(read) >= limit:
1565 idx = limit - datalen - 1
1566 # read more data
1567 data.append(read)
1568 read = self.readfunc()
1569 if not read:
1570 idx = 0 #eof condition
1571 break
1572 idx += 1
1573 data.append(read[:idx])
1574 self.remainder = read[idx:]
1575 return b"".join(data)
1576 except:
1577 self.remainder = b"".join(data)
1578 raise
1579
Berker Peksagbabc6882015-02-20 09:39:38 +02001580
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001581class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001582 def test_all(self):
1583 # Documented objects defined in the module should be in __all__
1584 expected = {"responses"} # White-list documented dict() object
1585 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1586 # intentionally omitted for simplicity
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001587 denylist = {"HTTPMessage", "parse_headers"}
Berker Peksagbabc6882015-02-20 09:39:38 +02001588 for name in dir(client):
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001589 if name.startswith("_") or name in denylist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001590 continue
1591 module_object = getattr(client, name)
1592 if getattr(module_object, "__module__", None) == "http.client":
1593 expected.add(name)
1594 self.assertCountEqual(client.__all__, expected)
1595
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001596 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001597 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001598
Berker Peksagabbf0f42015-02-20 14:57:31 +02001599 def test_client_constants(self):
1600 # Make sure we don't break backward compatibility with 3.4
1601 expected = [
1602 'CONTINUE',
1603 'SWITCHING_PROTOCOLS',
1604 'PROCESSING',
1605 'OK',
1606 'CREATED',
1607 'ACCEPTED',
1608 'NON_AUTHORITATIVE_INFORMATION',
1609 'NO_CONTENT',
1610 'RESET_CONTENT',
1611 'PARTIAL_CONTENT',
1612 'MULTI_STATUS',
1613 'IM_USED',
1614 'MULTIPLE_CHOICES',
1615 'MOVED_PERMANENTLY',
1616 'FOUND',
1617 'SEE_OTHER',
1618 'NOT_MODIFIED',
1619 'USE_PROXY',
1620 'TEMPORARY_REDIRECT',
1621 'BAD_REQUEST',
1622 'UNAUTHORIZED',
1623 'PAYMENT_REQUIRED',
1624 'FORBIDDEN',
1625 'NOT_FOUND',
1626 'METHOD_NOT_ALLOWED',
1627 'NOT_ACCEPTABLE',
1628 'PROXY_AUTHENTICATION_REQUIRED',
1629 'REQUEST_TIMEOUT',
1630 'CONFLICT',
1631 'GONE',
1632 'LENGTH_REQUIRED',
1633 'PRECONDITION_FAILED',
1634 'REQUEST_ENTITY_TOO_LARGE',
1635 'REQUEST_URI_TOO_LONG',
1636 'UNSUPPORTED_MEDIA_TYPE',
1637 'REQUESTED_RANGE_NOT_SATISFIABLE',
1638 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001639 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001640 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001641 'UNPROCESSABLE_ENTITY',
1642 'LOCKED',
1643 'FAILED_DEPENDENCY',
1644 'UPGRADE_REQUIRED',
1645 'PRECONDITION_REQUIRED',
1646 'TOO_MANY_REQUESTS',
1647 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001648 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001649 'INTERNAL_SERVER_ERROR',
1650 'NOT_IMPLEMENTED',
1651 'BAD_GATEWAY',
1652 'SERVICE_UNAVAILABLE',
1653 'GATEWAY_TIMEOUT',
1654 'HTTP_VERSION_NOT_SUPPORTED',
1655 'INSUFFICIENT_STORAGE',
1656 'NOT_EXTENDED',
1657 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001658 'EARLY_HINTS',
1659 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001660 ]
1661 for const in expected:
1662 with self.subTest(constant=const):
1663 self.assertTrue(hasattr(client, const))
1664
Gregory P. Smithb4066372010-01-03 03:28:29 +00001665
1666class SourceAddressTest(TestCase):
1667 def setUp(self):
1668 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001669 self.port = socket_helper.bind_port(self.serv)
1670 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001671 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001672 self.conn = None
1673
1674 def tearDown(self):
1675 if self.conn:
1676 self.conn.close()
1677 self.conn = None
1678 self.serv.close()
1679 self.serv = None
1680
1681 def testHTTPConnectionSourceAddress(self):
1682 self.conn = client.HTTPConnection(HOST, self.port,
1683 source_address=('', self.source_port))
1684 self.conn.connect()
1685 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1686
1687 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1688 'http.client.HTTPSConnection not defined')
1689 def testHTTPSConnectionSourceAddress(self):
1690 self.conn = client.HTTPSConnection(HOST, self.port,
1691 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001692 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001693 # this code doesn't deal with setting up an active running SSL server
1694 # for an ssl_wrapped connect() to actually return from.
1695
1696
Guido van Rossumd8faa362007-04-27 19:54:29 +00001697class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001698 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001699
1700 def setUp(self):
1701 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001702 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001703 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001704
1705 def tearDown(self):
1706 self.serv.close()
1707 self.serv = None
1708
1709 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001710 # This will prove that the timeout gets through HTTPConnection
1711 # and into the socket.
1712
Georg Brandlf78e02b2008-06-10 17:40:04 +00001713 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001714 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001715 socket.setdefaulttimeout(30)
1716 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001717 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001718 httpConn.connect()
1719 finally:
1720 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001721 self.assertEqual(httpConn.sock.gettimeout(), 30)
1722 httpConn.close()
1723
Georg Brandlf78e02b2008-06-10 17:40:04 +00001724 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001725 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001726 socket.setdefaulttimeout(30)
1727 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001728 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001729 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001730 httpConn.connect()
1731 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001732 socket.setdefaulttimeout(None)
1733 self.assertEqual(httpConn.sock.gettimeout(), None)
1734 httpConn.close()
1735
1736 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001737 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001738 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001739 self.assertEqual(httpConn.sock.gettimeout(), 30)
1740 httpConn.close()
1741
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001742
R David Murraycae7bdb2015-04-05 19:26:29 -04001743class PersistenceTest(TestCase):
1744
1745 def test_reuse_reconnect(self):
1746 # Should reuse or reconnect depending on header from server
1747 tests = (
1748 ('1.0', '', False),
1749 ('1.0', 'Connection: keep-alive\r\n', True),
1750 ('1.1', '', True),
1751 ('1.1', 'Connection: close\r\n', False),
1752 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1753 ('1.1', 'Connection: cloSE\r\n', False),
1754 )
1755 for version, header, reuse in tests:
1756 with self.subTest(version=version, header=header):
1757 msg = (
1758 'HTTP/{} 200 OK\r\n'
1759 '{}'
1760 'Content-Length: 12\r\n'
1761 '\r\n'
1762 'Dummy body\r\n'
1763 ).format(version, header)
1764 conn = FakeSocketHTTPConnection(msg)
1765 self.assertIsNone(conn.sock)
1766 conn.request('GET', '/open-connection')
1767 with conn.getresponse() as response:
1768 self.assertEqual(conn.sock is None, not reuse)
1769 response.read()
1770 self.assertEqual(conn.sock is None, not reuse)
1771 self.assertEqual(conn.connections, 1)
1772 conn.request('GET', '/subsequent-request')
1773 self.assertEqual(conn.connections, 1 if reuse else 2)
1774
1775 def test_disconnected(self):
1776
1777 def make_reset_reader(text):
1778 """Return BufferedReader that raises ECONNRESET at EOF"""
1779 stream = io.BytesIO(text)
1780 def readinto(buffer):
1781 size = io.BytesIO.readinto(stream, buffer)
1782 if size == 0:
1783 raise ConnectionResetError()
1784 return size
1785 stream.readinto = readinto
1786 return io.BufferedReader(stream)
1787
1788 tests = (
1789 (io.BytesIO, client.RemoteDisconnected),
1790 (make_reset_reader, ConnectionResetError),
1791 )
1792 for stream_factory, exception in tests:
1793 with self.subTest(exception=exception):
1794 conn = FakeSocketHTTPConnection(b'', stream_factory)
1795 conn.request('GET', '/eof-response')
1796 self.assertRaises(exception, conn.getresponse)
1797 self.assertIsNone(conn.sock)
1798 # HTTPConnection.connect() should be automatically invoked
1799 conn.request('GET', '/reconnect')
1800 self.assertEqual(conn.connections, 2)
1801
1802 def test_100_close(self):
1803 conn = FakeSocketHTTPConnection(
1804 b'HTTP/1.1 100 Continue\r\n'
1805 b'\r\n'
1806 # Missing final response
1807 )
1808 conn.request('GET', '/', headers={'Expect': '100-continue'})
1809 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1810 self.assertIsNone(conn.sock)
1811 conn.request('GET', '/reconnect')
1812 self.assertEqual(conn.connections, 2)
1813
1814
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001815class HTTPSTest(TestCase):
1816
1817 def setUp(self):
1818 if not hasattr(client, 'HTTPSConnection'):
1819 self.skipTest('ssl support required')
1820
1821 def make_server(self, certfile):
1822 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001823 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001824
1825 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001826 # simple test to check it's storing the timeout
1827 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1828 self.assertEqual(h.timeout, 30)
1829
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001830 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001831 # Default settings: requires a valid cert from a trusted CA
1832 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001833 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001834 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001835 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1836 with self.assertRaises(ssl.SSLError) as exc_info:
1837 h.request('GET', '/')
1838 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1839
1840 def test_networked_noverification(self):
1841 # Switch off cert verification
1842 import ssl
1843 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001844 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001845 context = ssl._create_unverified_context()
1846 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1847 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001848 h.request('GET', '/')
1849 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001850 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001851 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001852 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001853
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001854 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001855 def test_networked_trusted_by_default_cert(self):
1856 # Default settings: requires a valid cert from a trusted CA
1857 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001858 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001859 h = client.HTTPSConnection('www.python.org', 443)
1860 h.request('GET', '/')
1861 resp = h.getresponse()
1862 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001863 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001864 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001865 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001866
1867 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001868 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001869 import ssl
1870 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001871 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001872 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001873 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1874 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1875 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001876 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001877 try:
1878 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1879 context=context)
1880 h.request('GET', '/')
1881 resp = h.getresponse()
1882 except ssl.SSLError as ssl_err:
1883 ssl_err_str = str(ssl_err)
1884 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1885 # modern Linux distros (Debian Buster, etc) default OpenSSL
1886 # configurations it'll fail saying "key too weak" until we
1887 # address https://bugs.python.org/issue36816 to use a proper
1888 # key size on self-signed.pythontest.net.
1889 if re.search(r'(?i)key.too.weak', ssl_err_str):
1890 raise unittest.SkipTest(
1891 f'Got {ssl_err_str} trying to connect '
1892 f'to {selfsigned_pythontestdotnet}. '
1893 'See https://bugs.python.org/issue36816.')
1894 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001895 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001896 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001897 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001898 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001899
1900 def test_networked_bad_cert(self):
1901 # We feed a "CA" cert that is unrelated to the server's cert
1902 import ssl
1903 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001904 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001905 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001906 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001907 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1908 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001909 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001910 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1911
1912 def test_local_unknown_cert(self):
1913 # The custom cert isn't known to the default trust bundle
1914 import ssl
1915 server = self.make_server(CERT_localhost)
1916 h = client.HTTPSConnection('localhost', server.port)
1917 with self.assertRaises(ssl.SSLError) as exc_info:
1918 h.request('GET', '/')
1919 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001920
1921 def test_local_good_hostname(self):
1922 # The (valid) cert validates the HTTP hostname
1923 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001924 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001925 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001926 context.load_verify_locations(CERT_localhost)
1927 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001928 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001929 h.request('GET', '/nonexistent')
1930 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001931 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001932 self.assertEqual(resp.status, 404)
1933
1934 def test_local_bad_hostname(self):
1935 # The (valid) cert doesn't validate the HTTP hostname
1936 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001937 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001938 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001939 context.load_verify_locations(CERT_fakehostname)
1940 h = client.HTTPSConnection('localhost', server.port, context=context)
1941 with self.assertRaises(ssl.CertificateError):
1942 h.request('GET', '/')
1943 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001944 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001945 h = client.HTTPSConnection('localhost', server.port,
1946 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001947 with self.assertRaises(ssl.CertificateError):
1948 h.request('GET', '/')
1949 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001950 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001951 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001952 h = client.HTTPSConnection('localhost', server.port,
1953 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001954 h.request('GET', '/nonexistent')
1955 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001956 resp.close()
1957 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001958 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001959 # The context's check_hostname setting is used if one isn't passed to
1960 # HTTPSConnection.
1961 context.check_hostname = False
1962 h = client.HTTPSConnection('localhost', server.port, context=context)
1963 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001964 resp = h.getresponse()
1965 self.assertEqual(resp.status, 404)
1966 resp.close()
1967 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001968 # Passing check_hostname to HTTPSConnection should override the
1969 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001970 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001971 h = client.HTTPSConnection('localhost', server.port,
1972 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001973 with self.assertRaises(ssl.CertificateError):
1974 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001975
Petri Lehtinene119c402011-10-26 21:29:15 +03001976 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1977 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001978 def test_host_port(self):
1979 # Check invalid host_port
1980
1981 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1982 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1983
1984 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1985 "fe80::207:e9ff:fe9b", 8000),
1986 ("www.python.org:443", "www.python.org", 443),
1987 ("www.python.org:", "www.python.org", 443),
1988 ("www.python.org", "www.python.org", 443),
1989 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1990 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1991 443)):
1992 c = client.HTTPSConnection(hp)
1993 self.assertEqual(h, c.host)
1994 self.assertEqual(p, c.port)
1995
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001996 def test_tls13_pha(self):
1997 import ssl
1998 if not ssl.HAS_TLSv1_3:
1999 self.skipTest('TLS 1.3 support required')
2000 # just check status of PHA flag
2001 h = client.HTTPSConnection('localhost', 443)
2002 self.assertTrue(h._context.post_handshake_auth)
2003
2004 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2005 self.assertFalse(context.post_handshake_auth)
2006 h = client.HTTPSConnection('localhost', 443, context=context)
2007 self.assertIs(h._context, context)
2008 self.assertFalse(h._context.post_handshake_auth)
2009
Pablo Galindoaa542c22019-08-08 23:25:46 +01002010 with warnings.catch_warnings():
2011 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
2012 DeprecationWarning)
2013 h = client.HTTPSConnection('localhost', 443, context=context,
2014 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02002015 self.assertTrue(h._context.post_handshake_auth)
2016
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002017
Jeremy Hylton236654b2009-03-27 20:24:34 +00002018class RequestBodyTest(TestCase):
2019 """Test cases where a request includes a message body."""
2020
2021 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002022 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00002023 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00002024 self.conn.sock = self.sock
2025
2026 def get_headers_and_fp(self):
2027 f = io.BytesIO(self.sock.data)
2028 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002029 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00002030 return message, f
2031
Martin Panter3c0d0ba2016-08-24 06:33:33 +00002032 def test_list_body(self):
2033 # Note that no content-length is automatically calculated for
2034 # an iterable. The request will fall back to send chunked
2035 # transfer encoding.
2036 cases = (
2037 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2038 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2039 )
2040 for body, expected in cases:
2041 with self.subTest(body):
2042 self.conn = client.HTTPConnection('example.com')
2043 self.conn.sock = self.sock = FakeSocket('')
2044
2045 self.conn.request('PUT', '/url', body)
2046 msg, f = self.get_headers_and_fp()
2047 self.assertNotIn('Content-Type', msg)
2048 self.assertNotIn('Content-Length', msg)
2049 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
2050 self.assertEqual(expected, f.read())
2051
Jeremy Hylton236654b2009-03-27 20:24:34 +00002052 def test_manual_content_length(self):
2053 # Set an incorrect content-length so that we can verify that
2054 # it will not be over-ridden by the library.
2055 self.conn.request("PUT", "/url", "body",
2056 {"Content-Length": "42"})
2057 message, f = self.get_headers_and_fp()
2058 self.assertEqual("42", message.get("content-length"))
2059 self.assertEqual(4, len(f.read()))
2060
2061 def test_ascii_body(self):
2062 self.conn.request("PUT", "/url", "body")
2063 message, f = self.get_headers_and_fp()
2064 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002065 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002066 self.assertEqual("4", message.get("content-length"))
2067 self.assertEqual(b'body', f.read())
2068
2069 def test_latin1_body(self):
2070 self.conn.request("PUT", "/url", "body\xc1")
2071 message, f = self.get_headers_and_fp()
2072 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002073 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002074 self.assertEqual("5", message.get("content-length"))
2075 self.assertEqual(b'body\xc1', f.read())
2076
2077 def test_bytes_body(self):
2078 self.conn.request("PUT", "/url", b"body\xc1")
2079 message, f = self.get_headers_and_fp()
2080 self.assertEqual("text/plain", message.get_content_type())
Raymond 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
Martin Panteref91bb22016-08-27 01:39:26 +00002085 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08002086 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
Inada Naokifa51c0c2021-04-29 11:34:56 +09002087 with open(os_helper.TESTFN, "w", encoding="utf-8") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002088 f.write("body")
Inada Naokifa51c0c2021-04-29 11:34:56 +09002089 with open(os_helper.TESTFN, encoding="utf-8") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002090 self.conn.request("PUT", "/url", f)
2091 message, f = self.get_headers_and_fp()
2092 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002093 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00002094 # No content-length will be determined for files; the body
2095 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00002096 self.assertIsNone(message.get("content-length"))
2097 self.assertEqual("chunked", message.get("transfer-encoding"))
2098 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002099
2100 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08002101 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2102 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002103 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08002104 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00002105 self.conn.request("PUT", "/url", f)
2106 message, f = self.get_headers_and_fp()
2107 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00002108 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00002109 self.assertEqual("chunked", message.get("Transfer-Encoding"))
2110 self.assertNotIn("Content-Length", message)
2111 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00002112
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00002113
2114class HTTPResponseTest(TestCase):
2115
2116 def setUp(self):
2117 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
2118 second-value\r\n\r\nText"
2119 sock = FakeSocket(body)
2120 self.resp = client.HTTPResponse(sock)
2121 self.resp.begin()
2122
2123 def test_getting_header(self):
2124 header = self.resp.getheader('My-Header')
2125 self.assertEqual(header, 'first-value, second-value')
2126
2127 header = self.resp.getheader('My-Header', 'some default')
2128 self.assertEqual(header, 'first-value, second-value')
2129
2130 def test_getting_nonexistent_header_with_string_default(self):
2131 header = self.resp.getheader('No-Such-Header', 'default-value')
2132 self.assertEqual(header, 'default-value')
2133
2134 def test_getting_nonexistent_header_with_iterable_default(self):
2135 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
2136 self.assertEqual(header, 'default, values')
2137
2138 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
2139 self.assertEqual(header, 'default, values')
2140
2141 def test_getting_nonexistent_header_without_default(self):
2142 header = self.resp.getheader('No-Such-Header')
2143 self.assertEqual(header, None)
2144
2145 def test_getting_header_defaultint(self):
2146 header = self.resp.getheader('No-Such-Header',default=42)
2147 self.assertEqual(header, 42)
2148
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002149class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002150 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002151 response_text = (
2152 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
2153 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2154 'Content-Length: 42\r\n\r\n'
2155 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002156 self.host = 'proxy.com'
2157 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02002158 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002159
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002160 def tearDown(self):
2161 self.conn.close()
2162
Berker Peksagab53ab02015-02-03 12:22:11 +02002163 def _create_connection(self, response_text):
2164 def create_connection(address, timeout=None, source_address=None):
2165 return FakeSocket(response_text, host=address[0], port=address[1])
2166 return create_connection
2167
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002168 def test_set_tunnel_host_port_headers(self):
2169 tunnel_host = 'destination.com'
2170 tunnel_port = 8888
2171 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2172 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2173 headers=tunnel_headers)
2174 self.conn.request('HEAD', '/', '')
2175 self.assertEqual(self.conn.sock.host, self.host)
2176 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2177 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2178 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2179 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2180
2181 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002182 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002183 self.conn.connect()
2184 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002185 'destination.com')
2186
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002187 def test_connect_with_tunnel(self):
2188 self.conn.set_tunnel('destination.com')
2189 self.conn.request('HEAD', '/', '')
2190 self.assertEqual(self.conn.sock.host, self.host)
2191 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2192 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002193 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002194 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2195 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002196
2197 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002198 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002199
Gregory P. Smithc25910a2021-03-07 23:35:13 -08002200 def test_tunnel_connect_single_send_connection_setup(self):
2201 """Regresstion test for https://bugs.python.org/issue43332."""
2202 with mock.patch.object(self.conn, 'send') as mock_send:
2203 self.conn.set_tunnel('destination.com')
2204 self.conn.connect()
2205 self.conn.request('GET', '/')
2206 mock_send.assert_called()
2207 # Likely 2, but this test only cares about the first.
2208 self.assertGreater(
2209 len(mock_send.mock_calls), 1,
2210 msg=f'unexpected number of send calls: {mock_send.mock_calls}')
2211 proxy_setup_data_sent = mock_send.mock_calls[0][1][0]
2212 self.assertIn(b'CONNECT destination.com', proxy_setup_data_sent)
2213 self.assertTrue(
2214 proxy_setup_data_sent.endswith(b'\r\n\r\n'),
2215 msg=f'unexpected proxy data sent {proxy_setup_data_sent!r}')
2216
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002217 def test_connect_put_request(self):
2218 self.conn.set_tunnel('destination.com')
2219 self.conn.request('PUT', '/', '')
2220 self.assertEqual(self.conn.sock.host, self.host)
2221 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2222 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2223 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2224
Berker Peksagab53ab02015-02-03 12:22:11 +02002225 def test_tunnel_debuglog(self):
2226 expected_header = 'X-Dummy: 1'
2227 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2228
2229 self.conn.set_debuglevel(1)
2230 self.conn._create_connection = self._create_connection(response_text)
2231 self.conn.set_tunnel('destination.com')
2232
2233 with support.captured_stdout() as output:
2234 self.conn.request('PUT', '/', '')
2235 lines = output.getvalue().splitlines()
2236 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002237
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002238
Thomas Wouters89f507f2006-12-13 04:49:30 +00002239if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002240 unittest.main(verbosity=2)