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