Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 1 | import errno |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 2 | from http import client |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 3 | import io |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 4 | import itertools |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 5 | import os |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 6 | import array |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 7 | import socket |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 8 | |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 9 | import unittest |
| 10 | TestCase = unittest.TestCase |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 11 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 12 | from test import support |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 13 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 14 | here = os.path.dirname(__file__) |
| 15 | # Self-signed cert file for 'localhost' |
| 16 | CERT_localhost = os.path.join(here, 'keycert.pem') |
| 17 | # Self-signed cert file for 'fakehostname' |
| 18 | CERT_fakehostname = os.path.join(here, 'keycert2.pem') |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 19 | # Self-signed cert file for self-signed.pythontest.net |
| 20 | CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 21 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 22 | # constants for testing chunked encoding |
| 23 | chunked_start = ( |
| 24 | 'HTTP/1.1 200 OK\r\n' |
| 25 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 26 | 'a\r\n' |
| 27 | 'hello worl\r\n' |
| 28 | '3\r\n' |
| 29 | 'd! \r\n' |
| 30 | '8\r\n' |
| 31 | 'and now \r\n' |
| 32 | '22\r\n' |
| 33 | 'for something completely different\r\n' |
| 34 | ) |
| 35 | chunked_expected = b'hello world! and now for something completely different' |
| 36 | chunk_extension = ";foo=bar" |
| 37 | last_chunk = "0\r\n" |
| 38 | last_chunk_extended = "0" + chunk_extension + "\r\n" |
| 39 | trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n" |
| 40 | chunked_end = "\r\n" |
| 41 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 42 | HOST = support.HOST |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 43 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 44 | class FakeSocket: |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 45 | def __init__(self, text, fileclass=io.BytesIO, host=None, port=None): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 46 | if isinstance(text, str): |
Guido van Rossum | 39478e8 | 2007-08-27 17:23:59 +0000 | [diff] [blame] | 47 | text = text.encode("ascii") |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 48 | self.text = text |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 49 | self.fileclass = fileclass |
Martin v. Löwis | dd5a860 | 2007-06-30 09:22:09 +0000 | [diff] [blame] | 50 | self.data = b'' |
Antoine Pitrou | 90e4774 | 2013-01-02 22:10:47 +0100 | [diff] [blame] | 51 | self.sendall_calls = 0 |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 52 | self.file_closed = False |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 53 | self.host = host |
| 54 | self.port = port |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 55 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 56 | def sendall(self, data): |
Antoine Pitrou | 90e4774 | 2013-01-02 22:10:47 +0100 | [diff] [blame] | 57 | self.sendall_calls += 1 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 58 | self.data += data |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 59 | |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 60 | def makefile(self, mode, bufsize=None): |
| 61 | if mode != 'r' and mode != 'rb': |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 62 | raise client.UnimplementedFileMode() |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 63 | # keep the file around so we can check how much was read from it |
| 64 | self.file = self.fileclass(self.text) |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 65 | self.file.close = self.file_close #nerf close () |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 66 | return self.file |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 67 | |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 68 | def file_close(self): |
| 69 | self.file_closed = True |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 70 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 71 | def close(self): |
| 72 | pass |
| 73 | |
Benjamin Peterson | 9d8a3ad | 2015-01-23 11:02:57 -0500 | [diff] [blame] | 74 | def setsockopt(self, level, optname, value): |
| 75 | pass |
| 76 | |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 77 | class EPipeSocket(FakeSocket): |
| 78 | |
| 79 | def __init__(self, text, pipe_trigger): |
| 80 | # When sendall() is called with pipe_trigger, raise EPIPE. |
| 81 | FakeSocket.__init__(self, text) |
| 82 | self.pipe_trigger = pipe_trigger |
| 83 | |
| 84 | def sendall(self, data): |
| 85 | if self.pipe_trigger in data: |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 86 | raise OSError(errno.EPIPE, "gotcha") |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 87 | self.data += data |
| 88 | |
| 89 | def close(self): |
| 90 | pass |
| 91 | |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 92 | class NoEOFBytesIO(io.BytesIO): |
| 93 | """Like BytesIO, but raises AssertionError on EOF. |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 94 | |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 95 | This is used below to test that http.client doesn't try to read |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 96 | more from the underlying file than it should. |
| 97 | """ |
| 98 | def read(self, n=-1): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 99 | data = io.BytesIO.read(self, n) |
Jeremy Hylton | da3f228 | 2007-08-29 17:26:34 +0000 | [diff] [blame] | 100 | if data == b'': |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 101 | raise AssertionError('caller tried to read past EOF') |
| 102 | return data |
| 103 | |
| 104 | def readline(self, length=None): |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 105 | data = io.BytesIO.readline(self, length) |
Jeremy Hylton | da3f228 | 2007-08-29 17:26:34 +0000 | [diff] [blame] | 106 | if data == b'': |
Jeremy Hylton | 121d34a | 2003-07-08 12:36:58 +0000 | [diff] [blame] | 107 | raise AssertionError('caller tried to read past EOF') |
| 108 | return data |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 109 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 110 | class HeaderTests(TestCase): |
| 111 | def test_auto_headers(self): |
| 112 | # Some headers are added automatically, but should not be added by |
| 113 | # .request() if they are explicitly set. |
| 114 | |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 115 | class HeaderCountingBuffer(list): |
| 116 | def __init__(self): |
| 117 | self.count = {} |
| 118 | def append(self, item): |
Guido van Rossum | 022c474 | 2007-08-29 02:00:20 +0000 | [diff] [blame] | 119 | kv = item.split(b':') |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 120 | if len(kv) > 1: |
| 121 | # item is a 'Key: Value' header string |
Martin v. Löwis | dd5a860 | 2007-06-30 09:22:09 +0000 | [diff] [blame] | 122 | lcKey = kv[0].decode('ascii').lower() |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 123 | self.count.setdefault(lcKey, 0) |
| 124 | self.count[lcKey] += 1 |
| 125 | list.append(self, item) |
| 126 | |
| 127 | for explicit_header in True, False: |
| 128 | for header in 'Content-length', 'Host', 'Accept-encoding': |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 129 | conn = client.HTTPConnection('example.com') |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 130 | conn.sock = FakeSocket('blahblahblah') |
| 131 | conn._buffer = HeaderCountingBuffer() |
| 132 | |
| 133 | body = 'spamspamspam' |
| 134 | headers = {} |
| 135 | if explicit_header: |
| 136 | headers[header] = str(len(body)) |
| 137 | conn.request('POST', '/', body, headers) |
| 138 | self.assertEqual(conn._buffer.count[header.lower()], 1) |
| 139 | |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 140 | def test_content_length_0(self): |
| 141 | |
| 142 | class ContentLengthChecker(list): |
| 143 | def __init__(self): |
| 144 | list.__init__(self) |
| 145 | self.content_length = None |
| 146 | def append(self, item): |
| 147 | kv = item.split(b':', 1) |
| 148 | if len(kv) > 1 and kv[0].lower() == b'content-length': |
| 149 | self.content_length = kv[1].strip() |
| 150 | list.append(self, item) |
| 151 | |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 152 | # Here, we're testing that methods expecting a body get a |
| 153 | # content-length set to zero if the body is empty (either None or '') |
| 154 | bodies = (None, '') |
| 155 | methods_with_body = ('PUT', 'POST', 'PATCH') |
| 156 | for method, body in itertools.product(methods_with_body, bodies): |
| 157 | conn = client.HTTPConnection('example.com') |
| 158 | conn.sock = FakeSocket(None) |
| 159 | conn._buffer = ContentLengthChecker() |
| 160 | conn.request(method, '/', body) |
| 161 | self.assertEqual( |
| 162 | conn._buffer.content_length, b'0', |
| 163 | 'Header Content-Length incorrect on {}'.format(method) |
| 164 | ) |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 165 | |
R David Murray | beed840 | 2015-03-22 15:18:23 -0400 | [diff] [blame] | 166 | # For these methods, we make sure that content-length is not set when |
| 167 | # the body is None because it might cause unexpected behaviour on the |
| 168 | # server. |
| 169 | methods_without_body = ( |
| 170 | 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE', |
| 171 | ) |
| 172 | for method in methods_without_body: |
| 173 | conn = client.HTTPConnection('example.com') |
| 174 | conn.sock = FakeSocket(None) |
| 175 | conn._buffer = ContentLengthChecker() |
| 176 | conn.request(method, '/', None) |
| 177 | self.assertEqual( |
| 178 | conn._buffer.content_length, None, |
| 179 | 'Header Content-Length set for empty body on {}'.format(method) |
| 180 | ) |
| 181 | |
| 182 | # If the body is set to '', that's considered to be "present but |
| 183 | # empty" rather than "missing", so content length would be set, even |
| 184 | # for methods that don't expect a body. |
| 185 | for method in methods_without_body: |
| 186 | conn = client.HTTPConnection('example.com') |
| 187 | conn.sock = FakeSocket(None) |
| 188 | conn._buffer = ContentLengthChecker() |
| 189 | conn.request(method, '/', '') |
| 190 | self.assertEqual( |
| 191 | conn._buffer.content_length, b'0', |
| 192 | 'Header Content-Length incorrect on {}'.format(method) |
| 193 | ) |
| 194 | |
| 195 | # If the body is set, make sure Content-Length is set. |
| 196 | for method in itertools.chain(methods_without_body, methods_with_body): |
| 197 | conn = client.HTTPConnection('example.com') |
| 198 | conn.sock = FakeSocket(None) |
| 199 | conn._buffer = ContentLengthChecker() |
| 200 | conn.request(method, '/', ' ') |
| 201 | self.assertEqual( |
| 202 | conn._buffer.content_length, b'1', |
| 203 | 'Header Content-Length incorrect on {}'.format(method) |
| 204 | ) |
Senthil Kumaran | 5fa4a89 | 2012-05-19 16:58:09 +0800 | [diff] [blame] | 205 | |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 206 | def test_putheader(self): |
| 207 | conn = client.HTTPConnection('example.com') |
| 208 | conn.sock = FakeSocket(None) |
| 209 | conn.putrequest('GET','/') |
| 210 | conn.putheader('Content-length', 42) |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 211 | self.assertIn(b'Content-length: 42', conn._buffer) |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 212 | |
Serhiy Storchaka | a112a8a | 2015-03-12 11:13:36 +0200 | [diff] [blame] | 213 | conn.putheader('Foo', ' bar ') |
| 214 | self.assertIn(b'Foo: bar ', conn._buffer) |
| 215 | conn.putheader('Bar', '\tbaz\t') |
| 216 | self.assertIn(b'Bar: \tbaz\t', conn._buffer) |
| 217 | conn.putheader('Authorization', 'Bearer mytoken') |
| 218 | self.assertIn(b'Authorization: Bearer mytoken', conn._buffer) |
| 219 | conn.putheader('IterHeader', 'IterA', 'IterB') |
| 220 | self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer) |
| 221 | conn.putheader('LatinHeader', b'\xFF') |
| 222 | self.assertIn(b'LatinHeader: \xFF', conn._buffer) |
| 223 | conn.putheader('Utf8Header', b'\xc3\x80') |
| 224 | self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer) |
| 225 | conn.putheader('C1-Control', b'next\x85line') |
| 226 | self.assertIn(b'C1-Control: next\x85line', conn._buffer) |
| 227 | conn.putheader('Embedded-Fold-Space', 'is\r\n allowed') |
| 228 | self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer) |
| 229 | conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed') |
| 230 | self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer) |
| 231 | conn.putheader('Key Space', 'value') |
| 232 | self.assertIn(b'Key Space: value', conn._buffer) |
| 233 | conn.putheader('KeySpace ', 'value') |
| 234 | self.assertIn(b'KeySpace : value', conn._buffer) |
| 235 | conn.putheader(b'Nonbreak\xa0Space', 'value') |
| 236 | self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer) |
| 237 | conn.putheader(b'\xa0NonbreakSpace', 'value') |
| 238 | self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer) |
| 239 | |
Senthil Kumaran | 74ebd9e | 2010-11-13 12:27:49 +0000 | [diff] [blame] | 240 | def test_ipv6host_header(self): |
| 241 | # Default host header on IPv6 transaction should wrapped by [] if |
| 242 | # its actual IPv6 address |
| 243 | expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \ |
| 244 | b'Accept-Encoding: identity\r\n\r\n' |
| 245 | conn = client.HTTPConnection('[2001::]:81') |
| 246 | sock = FakeSocket('') |
| 247 | conn.sock = sock |
| 248 | conn.request('GET', '/foo') |
| 249 | self.assertTrue(sock.data.startswith(expected)) |
| 250 | |
| 251 | expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \ |
| 252 | b'Accept-Encoding: identity\r\n\r\n' |
| 253 | conn = client.HTTPConnection('[2001:102A::]') |
| 254 | sock = FakeSocket('') |
| 255 | conn.sock = sock |
| 256 | conn.request('GET', '/foo') |
| 257 | self.assertTrue(sock.data.startswith(expected)) |
| 258 | |
Benjamin Peterson | 155ceaa | 2015-01-25 23:30:30 -0500 | [diff] [blame] | 259 | def test_malformed_headers_coped_with(self): |
| 260 | # Issue 19996 |
| 261 | body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n" |
| 262 | sock = FakeSocket(body) |
| 263 | resp = client.HTTPResponse(sock) |
| 264 | resp.begin() |
| 265 | |
| 266 | self.assertEqual(resp.getheader('First'), 'val') |
| 267 | self.assertEqual(resp.getheader('Second'), 'val') |
| 268 | |
Serhiy Storchaka | a112a8a | 2015-03-12 11:13:36 +0200 | [diff] [blame] | 269 | def test_invalid_headers(self): |
| 270 | conn = client.HTTPConnection('example.com') |
| 271 | conn.sock = FakeSocket('') |
| 272 | conn.putrequest('GET', '/') |
| 273 | |
| 274 | # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no |
| 275 | # longer allowed in header names |
| 276 | cases = ( |
| 277 | (b'Invalid\r\nName', b'ValidValue'), |
| 278 | (b'Invalid\rName', b'ValidValue'), |
| 279 | (b'Invalid\nName', b'ValidValue'), |
| 280 | (b'\r\nInvalidName', b'ValidValue'), |
| 281 | (b'\rInvalidName', b'ValidValue'), |
| 282 | (b'\nInvalidName', b'ValidValue'), |
| 283 | (b' InvalidName', b'ValidValue'), |
| 284 | (b'\tInvalidName', b'ValidValue'), |
| 285 | (b'Invalid:Name', b'ValidValue'), |
| 286 | (b':InvalidName', b'ValidValue'), |
| 287 | (b'ValidName', b'Invalid\r\nValue'), |
| 288 | (b'ValidName', b'Invalid\rValue'), |
| 289 | (b'ValidName', b'Invalid\nValue'), |
| 290 | (b'ValidName', b'InvalidValue\r\n'), |
| 291 | (b'ValidName', b'InvalidValue\r'), |
| 292 | (b'ValidName', b'InvalidValue\n'), |
| 293 | ) |
| 294 | for name, value in cases: |
| 295 | with self.subTest((name, value)): |
| 296 | with self.assertRaisesRegex(ValueError, 'Invalid header'): |
| 297 | conn.putheader(name, value) |
| 298 | |
Senthil Kumaran | 58d5dbf | 2010-10-03 18:22:42 +0000 | [diff] [blame] | 299 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 300 | class BasicTest(TestCase): |
| 301 | def test_status_lines(self): |
| 302 | # Test HTTP status lines |
Jeremy Hylton | 79fa2b6 | 2001-04-13 14:57:44 +0000 | [diff] [blame] | 303 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 304 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 305 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 306 | resp = client.HTTPResponse(sock) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 307 | resp.begin() |
Serhiy Storchaka | 1c84ac1 | 2013-12-17 21:50:02 +0200 | [diff] [blame] | 308 | self.assertEqual(resp.read(0), b'') # Issue #20007 |
| 309 | self.assertFalse(resp.isclosed()) |
| 310 | self.assertFalse(resp.closed) |
Jeremy Hylton | 8fff792 | 2007-08-03 20:56:14 +0000 | [diff] [blame] | 311 | self.assertEqual(resp.read(), b"Text") |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 312 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 313 | self.assertFalse(resp.closed) |
| 314 | resp.close() |
| 315 | self.assertTrue(resp.closed) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 316 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 317 | body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" |
| 318 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 319 | resp = client.HTTPResponse(sock) |
| 320 | self.assertRaises(client.BadStatusLine, resp.begin) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 321 | |
Benjamin Peterson | 11dbfd4 | 2010-03-21 22:50:04 +0000 | [diff] [blame] | 322 | def test_bad_status_repr(self): |
| 323 | exc = client.BadStatusLine('') |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 324 | self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''') |
Benjamin Peterson | 11dbfd4 | 2010-03-21 22:50:04 +0000 | [diff] [blame] | 325 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 326 | def test_partial_reads(self): |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 327 | # if we have a length, the system knows when to close itself |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 328 | # same behaviour than when we read the whole thing with read() |
| 329 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" |
| 330 | sock = FakeSocket(body) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 331 | resp = client.HTTPResponse(sock) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 332 | resp.begin() |
| 333 | self.assertEqual(resp.read(2), b'Te') |
| 334 | self.assertFalse(resp.isclosed()) |
| 335 | self.assertEqual(resp.read(2), b'xt') |
| 336 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 337 | self.assertFalse(resp.closed) |
| 338 | resp.close() |
| 339 | self.assertTrue(resp.closed) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 340 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 341 | def test_partial_readintos(self): |
Antoine Pitrou | d20e774 | 2012-12-15 19:22:30 +0100 | [diff] [blame] | 342 | # if we have a length, the system knows when to close itself |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 343 | # same behaviour than when we read the whole thing with read() |
| 344 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" |
| 345 | sock = FakeSocket(body) |
| 346 | resp = client.HTTPResponse(sock) |
| 347 | resp.begin() |
| 348 | b = bytearray(2) |
| 349 | n = resp.readinto(b) |
| 350 | self.assertEqual(n, 2) |
| 351 | self.assertEqual(bytes(b), b'Te') |
| 352 | self.assertFalse(resp.isclosed()) |
| 353 | n = resp.readinto(b) |
| 354 | self.assertEqual(n, 2) |
| 355 | self.assertEqual(bytes(b), b'xt') |
| 356 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b6c86fd | 2013-02-06 10:35:40 +0200 | [diff] [blame] | 357 | self.assertFalse(resp.closed) |
| 358 | resp.close() |
| 359 | self.assertTrue(resp.closed) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 360 | |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 361 | def test_partial_reads_no_content_length(self): |
| 362 | # when no length is present, the socket should be gracefully closed when |
| 363 | # all data was read |
| 364 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 365 | sock = FakeSocket(body) |
| 366 | resp = client.HTTPResponse(sock) |
| 367 | resp.begin() |
| 368 | self.assertEqual(resp.read(2), b'Te') |
| 369 | self.assertFalse(resp.isclosed()) |
| 370 | self.assertEqual(resp.read(2), b'xt') |
| 371 | self.assertEqual(resp.read(1), b'') |
| 372 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 373 | self.assertFalse(resp.closed) |
| 374 | resp.close() |
| 375 | self.assertTrue(resp.closed) |
Antoine Pitrou | 084daa2 | 2012-12-15 19:11:54 +0100 | [diff] [blame] | 376 | |
Antoine Pitrou | d20e774 | 2012-12-15 19:22:30 +0100 | [diff] [blame] | 377 | def test_partial_readintos_no_content_length(self): |
| 378 | # when no length is present, the socket should be gracefully closed when |
| 379 | # all data was read |
| 380 | body = "HTTP/1.1 200 Ok\r\n\r\nText" |
| 381 | sock = FakeSocket(body) |
| 382 | resp = client.HTTPResponse(sock) |
| 383 | resp.begin() |
| 384 | b = bytearray(2) |
| 385 | n = resp.readinto(b) |
| 386 | self.assertEqual(n, 2) |
| 387 | self.assertEqual(bytes(b), b'Te') |
| 388 | self.assertFalse(resp.isclosed()) |
| 389 | n = resp.readinto(b) |
| 390 | self.assertEqual(n, 2) |
| 391 | self.assertEqual(bytes(b), b'xt') |
| 392 | n = resp.readinto(b) |
| 393 | self.assertEqual(n, 0) |
| 394 | self.assertTrue(resp.isclosed()) |
| 395 | |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 396 | def test_partial_reads_incomplete_body(self): |
| 397 | # if the server shuts down the connection before the whole |
| 398 | # content-length is delivered, the socket is gracefully closed |
| 399 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" |
| 400 | sock = FakeSocket(body) |
| 401 | resp = client.HTTPResponse(sock) |
| 402 | resp.begin() |
| 403 | self.assertEqual(resp.read(2), b'Te') |
| 404 | self.assertFalse(resp.isclosed()) |
| 405 | self.assertEqual(resp.read(2), b'xt') |
| 406 | self.assertEqual(resp.read(1), b'') |
| 407 | self.assertTrue(resp.isclosed()) |
| 408 | |
Antoine Pitrou | 6a35e18 | 2013-02-02 23:04:56 +0100 | [diff] [blame] | 409 | def test_partial_readintos_incomplete_body(self): |
| 410 | # if the server shuts down the connection before the whole |
| 411 | # content-length is delivered, the socket is gracefully closed |
| 412 | body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText" |
| 413 | sock = FakeSocket(body) |
| 414 | resp = client.HTTPResponse(sock) |
| 415 | resp.begin() |
| 416 | b = bytearray(2) |
| 417 | n = resp.readinto(b) |
| 418 | self.assertEqual(n, 2) |
| 419 | self.assertEqual(bytes(b), b'Te') |
| 420 | self.assertFalse(resp.isclosed()) |
| 421 | n = resp.readinto(b) |
| 422 | self.assertEqual(n, 2) |
| 423 | self.assertEqual(bytes(b), b'xt') |
| 424 | n = resp.readinto(b) |
| 425 | self.assertEqual(n, 0) |
| 426 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 427 | self.assertFalse(resp.closed) |
| 428 | resp.close() |
| 429 | self.assertTrue(resp.closed) |
Antoine Pitrou | 6a35e18 | 2013-02-02 23:04:56 +0100 | [diff] [blame] | 430 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 431 | def test_host_port(self): |
| 432 | # Check invalid host_port |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 433 | |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 434 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 435 | self.assertRaises(client.InvalidURL, client.HTTPConnection, hp) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 436 | |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 437 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", |
| 438 | "fe80::207:e9ff:fe9b", 8000), |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 439 | ("www.python.org:80", "www.python.org", 80), |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 440 | ("www.python.org:", "www.python.org", 80), |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 441 | ("www.python.org", "www.python.org", 80), |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 442 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80), |
| 443 | ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 444 | c = client.HTTPConnection(hp) |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 445 | self.assertEqual(h, c.host) |
| 446 | self.assertEqual(p, c.port) |
Skip Montanaro | 10e6e0e | 2004-09-14 16:32:02 +0000 | [diff] [blame] | 447 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 448 | def test_response_headers(self): |
| 449 | # test response with multiple message headers with the same field name. |
| 450 | text = ('HTTP/1.1 200 OK\r\n' |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 451 | 'Set-Cookie: Customer="WILE_E_COYOTE"; ' |
| 452 | 'Version="1"; Path="/acme"\r\n' |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 453 | 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' |
| 454 | ' Path="/acme"\r\n' |
| 455 | '\r\n' |
| 456 | 'No body\r\n') |
| 457 | hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' |
| 458 | ', ' |
| 459 | 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') |
| 460 | s = FakeSocket(text) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 461 | r = client.HTTPResponse(s) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 462 | r.begin() |
| 463 | cookies = r.getheader("Set-Cookie") |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 464 | self.assertEqual(cookies, hdr) |
Jeremy Hylton | ba60319 | 2003-01-23 18:02:20 +0000 | [diff] [blame] | 465 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 466 | def test_read_head(self): |
| 467 | # Test that the library doesn't attempt to read any data |
| 468 | # from a HEAD request. (Tickles SF bug #622042.) |
| 469 | sock = FakeSocket( |
| 470 | 'HTTP/1.1 200 OK\r\n' |
| 471 | 'Content-Length: 14432\r\n' |
| 472 | '\r\n', |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 473 | NoEOFBytesIO) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 474 | resp = client.HTTPResponse(sock, method="HEAD") |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 475 | resp.begin() |
Guido van Rossum | a00f123 | 2007-09-12 19:43:09 +0000 | [diff] [blame] | 476 | if resp.read(): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 477 | self.fail("Did not expect response from HEAD request") |
Jeremy Hylton | c1b2cb9 | 2003-05-05 16:13:58 +0000 | [diff] [blame] | 478 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 479 | def test_readinto_head(self): |
| 480 | # Test that the library doesn't attempt to read any data |
| 481 | # from a HEAD request. (Tickles SF bug #622042.) |
| 482 | sock = FakeSocket( |
| 483 | 'HTTP/1.1 200 OK\r\n' |
| 484 | 'Content-Length: 14432\r\n' |
| 485 | '\r\n', |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 486 | NoEOFBytesIO) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 487 | resp = client.HTTPResponse(sock, method="HEAD") |
| 488 | resp.begin() |
| 489 | b = bytearray(5) |
| 490 | if resp.readinto(b) != 0: |
| 491 | self.fail("Did not expect response from HEAD request") |
| 492 | self.assertEqual(bytes(b), b'\x00'*5) |
| 493 | |
Georg Brandl | bf3f8eb | 2013-10-27 07:34:48 +0100 | [diff] [blame] | 494 | def test_too_many_headers(self): |
| 495 | headers = '\r\n'.join('Header%d: foo' % i |
| 496 | for i in range(client._MAXHEADERS + 1)) + '\r\n' |
| 497 | text = ('HTTP/1.1 200 OK\r\n' + headers) |
| 498 | s = FakeSocket(text) |
| 499 | r = client.HTTPResponse(s) |
| 500 | self.assertRaisesRegex(client.HTTPException, |
| 501 | r"got more than \d+ headers", r.begin) |
| 502 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 503 | def test_send_file(self): |
Guido van Rossum | 022c474 | 2007-08-29 02:00:20 +0000 | [diff] [blame] | 504 | expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' |
| 505 | b'Accept-Encoding: identity\r\nContent-Length:') |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 506 | |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 507 | with open(__file__, 'rb') as body: |
| 508 | conn = client.HTTPConnection('example.com') |
| 509 | sock = FakeSocket(body) |
| 510 | conn.sock = sock |
| 511 | conn.request('GET', '/foo', body) |
| 512 | self.assertTrue(sock.data.startswith(expected), '%r != %r' % |
| 513 | (sock.data[:len(expected)], expected)) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 514 | |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 515 | def test_send(self): |
| 516 | expected = b'this is a test this is only a test' |
| 517 | conn = client.HTTPConnection('example.com') |
| 518 | sock = FakeSocket(None) |
| 519 | conn.sock = sock |
| 520 | conn.send(expected) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 521 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 522 | sock.data = b'' |
| 523 | conn.send(array.array('b', expected)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 524 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 525 | sock.data = b'' |
| 526 | conn.send(io.BytesIO(expected)) |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 527 | self.assertEqual(expected, sock.data) |
Antoine Pitrou | ead1d62 | 2009-09-29 18:44:53 +0000 | [diff] [blame] | 528 | |
Andrew Svetlov | 7b2c8bb | 2013-04-12 22:49:19 +0300 | [diff] [blame] | 529 | def test_send_updating_file(self): |
| 530 | def data(): |
| 531 | yield 'data' |
| 532 | yield None |
| 533 | yield 'data_two' |
| 534 | |
| 535 | class UpdatingFile(): |
| 536 | mode = 'r' |
| 537 | d = data() |
| 538 | def read(self, blocksize=-1): |
| 539 | return self.d.__next__() |
| 540 | |
| 541 | expected = b'data' |
| 542 | |
| 543 | conn = client.HTTPConnection('example.com') |
| 544 | sock = FakeSocket("") |
| 545 | conn.sock = sock |
| 546 | conn.send(UpdatingFile()) |
| 547 | self.assertEqual(sock.data, expected) |
| 548 | |
| 549 | |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 550 | def test_send_iter(self): |
| 551 | expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ |
| 552 | b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \ |
| 553 | b'\r\nonetwothree' |
| 554 | |
| 555 | def body(): |
| 556 | yield b"one" |
| 557 | yield b"two" |
| 558 | yield b"three" |
| 559 | |
| 560 | conn = client.HTTPConnection('example.com') |
| 561 | sock = FakeSocket("") |
| 562 | conn.sock = sock |
| 563 | conn.request('GET', '/foo', body(), {'Content-Length': '11'}) |
Victor Stinner | 04ba966 | 2011-01-04 00:04:46 +0000 | [diff] [blame] | 564 | self.assertEqual(sock.data, expected) |
Senthil Kumaran | 7bc0d87 | 2010-12-19 10:49:52 +0000 | [diff] [blame] | 565 | |
Senthil Kumaran | eb71ad4 | 2011-08-02 18:33:41 +0800 | [diff] [blame] | 566 | def test_send_type_error(self): |
| 567 | # See: Issue #12676 |
| 568 | conn = client.HTTPConnection('example.com') |
| 569 | conn.sock = FakeSocket('') |
| 570 | with self.assertRaises(TypeError): |
| 571 | conn.request('POST', 'test', conn) |
| 572 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 573 | def test_chunked(self): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 574 | expected = chunked_expected |
| 575 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 576 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 577 | resp.begin() |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 578 | self.assertEqual(resp.read(), expected) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 579 | resp.close() |
| 580 | |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 581 | # Various read sizes |
| 582 | for n in range(1, 12): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 583 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 584 | resp = client.HTTPResponse(sock, method="GET") |
| 585 | resp.begin() |
| 586 | self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected) |
| 587 | resp.close() |
| 588 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 589 | for x in ('', 'foo\r\n'): |
| 590 | sock = FakeSocket(chunked_start + x) |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 591 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 592 | resp.begin() |
| 593 | try: |
| 594 | resp.read() |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 595 | except client.IncompleteRead as i: |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 596 | self.assertEqual(i.partial, expected) |
| 597 | expected_message = 'IncompleteRead(%d bytes read)' % len(expected) |
| 598 | self.assertEqual(repr(i), expected_message) |
| 599 | self.assertEqual(str(i), expected_message) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 600 | else: |
| 601 | self.fail('IncompleteRead expected') |
| 602 | finally: |
| 603 | resp.close() |
| 604 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 605 | def test_readinto_chunked(self): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 606 | |
| 607 | expected = chunked_expected |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 608 | nexpected = len(expected) |
| 609 | b = bytearray(128) |
| 610 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 611 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 612 | resp = client.HTTPResponse(sock, method="GET") |
| 613 | resp.begin() |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 614 | n = resp.readinto(b) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 615 | self.assertEqual(b[:nexpected], expected) |
| 616 | self.assertEqual(n, nexpected) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 617 | resp.close() |
| 618 | |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 619 | # Various read sizes |
| 620 | for n in range(1, 12): |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 621 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 622 | resp = client.HTTPResponse(sock, method="GET") |
| 623 | resp.begin() |
| 624 | m = memoryview(b) |
| 625 | i = resp.readinto(m[0:n]) |
| 626 | i += resp.readinto(m[i:n + i]) |
| 627 | i += resp.readinto(m[i:]) |
| 628 | self.assertEqual(b[:nexpected], expected) |
| 629 | self.assertEqual(i, nexpected) |
| 630 | resp.close() |
| 631 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 632 | for x in ('', 'foo\r\n'): |
| 633 | sock = FakeSocket(chunked_start + x) |
| 634 | resp = client.HTTPResponse(sock, method="GET") |
| 635 | resp.begin() |
| 636 | try: |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 637 | n = resp.readinto(b) |
| 638 | except client.IncompleteRead as i: |
Antoine Pitrou | f7e7818 | 2012-01-04 18:57:22 +0100 | [diff] [blame] | 639 | self.assertEqual(i.partial, expected) |
| 640 | expected_message = 'IncompleteRead(%d bytes read)' % len(expected) |
| 641 | self.assertEqual(repr(i), expected_message) |
| 642 | self.assertEqual(str(i), expected_message) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 643 | else: |
| 644 | self.fail('IncompleteRead expected') |
| 645 | finally: |
| 646 | resp.close() |
| 647 | |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 648 | def test_chunked_head(self): |
| 649 | chunked_start = ( |
| 650 | 'HTTP/1.1 200 OK\r\n' |
| 651 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 652 | 'a\r\n' |
| 653 | 'hello world\r\n' |
| 654 | '1\r\n' |
| 655 | 'd\r\n' |
| 656 | ) |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 657 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 658 | resp = client.HTTPResponse(sock, method="HEAD") |
| 659 | resp.begin() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 660 | self.assertEqual(resp.read(), b'') |
| 661 | self.assertEqual(resp.status, 200) |
| 662 | self.assertEqual(resp.reason, 'OK') |
Senthil Kumaran | 0b99883 | 2010-06-04 17:27:11 +0000 | [diff] [blame] | 663 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 664 | self.assertFalse(resp.closed) |
| 665 | resp.close() |
| 666 | self.assertTrue(resp.closed) |
Senthil Kumaran | 71fb6c8 | 2010-04-28 17:39:48 +0000 | [diff] [blame] | 667 | |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 668 | def test_readinto_chunked_head(self): |
| 669 | chunked_start = ( |
| 670 | 'HTTP/1.1 200 OK\r\n' |
| 671 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 672 | 'a\r\n' |
| 673 | 'hello world\r\n' |
| 674 | '1\r\n' |
| 675 | 'd\r\n' |
| 676 | ) |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 677 | sock = FakeSocket(chunked_start + last_chunk + chunked_end) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 678 | resp = client.HTTPResponse(sock, method="HEAD") |
| 679 | resp.begin() |
| 680 | b = bytearray(5) |
| 681 | n = resp.readinto(b) |
| 682 | self.assertEqual(n, 0) |
| 683 | self.assertEqual(bytes(b), b'\x00'*5) |
| 684 | self.assertEqual(resp.status, 200) |
| 685 | self.assertEqual(resp.reason, 'OK') |
| 686 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b6c86fd | 2013-02-06 10:35:40 +0200 | [diff] [blame] | 687 | self.assertFalse(resp.closed) |
| 688 | resp.close() |
| 689 | self.assertTrue(resp.closed) |
Antoine Pitrou | 38d9643 | 2011-12-06 22:33:57 +0100 | [diff] [blame] | 690 | |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 691 | def test_negative_content_length(self): |
Jeremy Hylton | 8206695 | 2008-12-15 03:08:30 +0000 | [diff] [blame] | 692 | sock = FakeSocket( |
| 693 | 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 694 | resp = client.HTTPResponse(sock, method="GET") |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 695 | resp.begin() |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 696 | self.assertEqual(resp.read(), b'Hello\r\n') |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 697 | self.assertTrue(resp.isclosed()) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 698 | |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 699 | def test_incomplete_read(self): |
| 700 | sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n') |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 701 | resp = client.HTTPResponse(sock, method="GET") |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 702 | resp.begin() |
| 703 | try: |
| 704 | resp.read() |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 705 | except client.IncompleteRead as i: |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 706 | self.assertEqual(i.partial, b'Hello\r\n') |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 707 | self.assertEqual(repr(i), |
| 708 | "IncompleteRead(7 bytes read, 3 more expected)") |
| 709 | self.assertEqual(str(i), |
| 710 | "IncompleteRead(7 bytes read, 3 more expected)") |
Antoine Pitrou | beec61a | 2013-02-02 22:49:34 +0100 | [diff] [blame] | 711 | self.assertTrue(resp.isclosed()) |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 712 | else: |
| 713 | self.fail('IncompleteRead expected') |
Benjamin Peterson | 6accb98 | 2009-03-02 22:50:25 +0000 | [diff] [blame] | 714 | |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 715 | def test_epipe(self): |
| 716 | sock = EPipeSocket( |
| 717 | "HTTP/1.0 401 Authorization Required\r\n" |
| 718 | "Content-type: text/html\r\n" |
| 719 | "WWW-Authenticate: Basic realm=\"example\"\r\n", |
| 720 | b"Content-Length") |
| 721 | conn = client.HTTPConnection("example.com") |
| 722 | conn.sock = sock |
Andrew Svetlov | 0832af6 | 2012-12-18 23:10:48 +0200 | [diff] [blame] | 723 | self.assertRaises(OSError, |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 724 | lambda: conn.request("PUT", "/url", "body")) |
| 725 | resp = conn.getresponse() |
| 726 | self.assertEqual(401, resp.status) |
| 727 | self.assertEqual("Basic realm=\"example\"", |
| 728 | resp.getheader("www-authenticate")) |
Christian Heimes | a612dc0 | 2008-02-24 13:08:18 +0000 | [diff] [blame] | 729 | |
Senthil Kumaran | 5466bf1 | 2010-12-18 16:55:23 +0000 | [diff] [blame] | 730 | # Test lines overflowing the max line size (_MAXLINE in http.client) |
| 731 | |
| 732 | def test_overflowing_status_line(self): |
| 733 | body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n" |
| 734 | resp = client.HTTPResponse(FakeSocket(body)) |
| 735 | self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin) |
| 736 | |
| 737 | def test_overflowing_header_line(self): |
| 738 | body = ( |
| 739 | 'HTTP/1.1 200 OK\r\n' |
| 740 | 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n' |
| 741 | ) |
| 742 | resp = client.HTTPResponse(FakeSocket(body)) |
| 743 | self.assertRaises(client.LineTooLong, resp.begin) |
| 744 | |
| 745 | def test_overflowing_chunked_line(self): |
| 746 | body = ( |
| 747 | 'HTTP/1.1 200 OK\r\n' |
| 748 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 749 | + '0' * 65536 + 'a\r\n' |
| 750 | 'hello world\r\n' |
| 751 | '0\r\n' |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 752 | '\r\n' |
Senthil Kumaran | 5466bf1 | 2010-12-18 16:55:23 +0000 | [diff] [blame] | 753 | ) |
| 754 | resp = client.HTTPResponse(FakeSocket(body)) |
| 755 | resp.begin() |
| 756 | self.assertRaises(client.LineTooLong, resp.read) |
| 757 | |
Senthil Kumaran | 9c29f86 | 2012-04-29 10:20:46 +0800 | [diff] [blame] | 758 | def test_early_eof(self): |
| 759 | # Test httpresponse with no \r\n termination, |
| 760 | body = "HTTP/1.1 200 Ok" |
| 761 | sock = FakeSocket(body) |
| 762 | resp = client.HTTPResponse(sock) |
| 763 | resp.begin() |
| 764 | self.assertEqual(resp.read(), b'') |
| 765 | self.assertTrue(resp.isclosed()) |
Serhiy Storchaka | b5b9c8c | 2013-02-06 10:31:57 +0200 | [diff] [blame] | 766 | self.assertFalse(resp.closed) |
| 767 | resp.close() |
| 768 | self.assertTrue(resp.closed) |
Senthil Kumaran | 9c29f86 | 2012-04-29 10:20:46 +0800 | [diff] [blame] | 769 | |
Serhiy Storchaka | b491e05 | 2014-12-01 13:07:45 +0200 | [diff] [blame] | 770 | def test_error_leak(self): |
| 771 | # Test that the socket is not leaked if getresponse() fails |
| 772 | conn = client.HTTPConnection('example.com') |
| 773 | response = None |
| 774 | class Response(client.HTTPResponse): |
| 775 | def __init__(self, *pos, **kw): |
| 776 | nonlocal response |
| 777 | response = self # Avoid garbage collector closing the socket |
| 778 | client.HTTPResponse.__init__(self, *pos, **kw) |
| 779 | conn.response_class = Response |
| 780 | conn.sock = FakeSocket('') # Emulate server dropping connection |
| 781 | conn.request('GET', '/') |
| 782 | self.assertRaises(client.BadStatusLine, conn.getresponse) |
| 783 | self.assertTrue(response.closed) |
| 784 | self.assertTrue(conn.sock.file_closed) |
| 785 | |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 786 | def test_chunked_extension(self): |
| 787 | extra = '3;foo=bar\r\n' + 'abc\r\n' |
| 788 | expected = chunked_expected + b'abc' |
| 789 | |
| 790 | sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end) |
| 791 | resp = client.HTTPResponse(sock, method="GET") |
| 792 | resp.begin() |
| 793 | self.assertEqual(resp.read(), expected) |
| 794 | resp.close() |
| 795 | |
| 796 | def test_chunked_missing_end(self): |
| 797 | """some servers may serve up a short chunked encoding stream""" |
| 798 | expected = chunked_expected |
| 799 | sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf |
| 800 | resp = client.HTTPResponse(sock, method="GET") |
| 801 | resp.begin() |
| 802 | self.assertEqual(resp.read(), expected) |
| 803 | resp.close() |
| 804 | |
| 805 | def test_chunked_trailers(self): |
| 806 | """See that trailers are read and ignored""" |
| 807 | expected = chunked_expected |
| 808 | sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end) |
| 809 | resp = client.HTTPResponse(sock, method="GET") |
| 810 | resp.begin() |
| 811 | self.assertEqual(resp.read(), expected) |
| 812 | # we should have reached the end of the file |
| 813 | self.assertEqual(sock.file.read(100), b"") #we read to the end |
| 814 | resp.close() |
| 815 | |
| 816 | def test_chunked_sync(self): |
| 817 | """Check that we don't read past the end of the chunked-encoding stream""" |
| 818 | expected = chunked_expected |
| 819 | extradata = "extradata" |
| 820 | sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata) |
| 821 | resp = client.HTTPResponse(sock, method="GET") |
| 822 | resp.begin() |
| 823 | self.assertEqual(resp.read(), expected) |
| 824 | # the file should now have our extradata ready to be read |
| 825 | self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end |
| 826 | resp.close() |
| 827 | |
| 828 | def test_content_length_sync(self): |
| 829 | """Check that we don't read past the end of the Content-Length stream""" |
| 830 | extradata = "extradata" |
| 831 | expected = b"Hello123\r\n" |
| 832 | sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello123\r\n' + extradata) |
| 833 | resp = client.HTTPResponse(sock, method="GET") |
| 834 | resp.begin() |
| 835 | self.assertEqual(resp.read(), expected) |
| 836 | # the file should now have our extradata ready to be read |
| 837 | self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end |
| 838 | resp.close() |
| 839 | |
| 840 | class ExtendedReadTest(TestCase): |
| 841 | """ |
| 842 | Test peek(), read1(), readline() |
| 843 | """ |
| 844 | lines = ( |
| 845 | 'HTTP/1.1 200 OK\r\n' |
| 846 | '\r\n' |
| 847 | 'hello world!\n' |
| 848 | 'and now \n' |
| 849 | 'for something completely different\n' |
| 850 | 'foo' |
| 851 | ) |
| 852 | lines_expected = lines[lines.find('hello'):].encode("ascii") |
| 853 | lines_chunked = ( |
| 854 | 'HTTP/1.1 200 OK\r\n' |
| 855 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 856 | 'a\r\n' |
| 857 | 'hello worl\r\n' |
| 858 | '3\r\n' |
| 859 | 'd!\n\r\n' |
| 860 | '9\r\n' |
| 861 | 'and now \n\r\n' |
| 862 | '23\r\n' |
| 863 | 'for something completely different\n\r\n' |
| 864 | '3\r\n' |
| 865 | 'foo\r\n' |
| 866 | '0\r\n' # terminating chunk |
| 867 | '\r\n' # end of trailers |
| 868 | ) |
| 869 | |
| 870 | def setUp(self): |
| 871 | sock = FakeSocket(self.lines) |
| 872 | resp = client.HTTPResponse(sock, method="GET") |
| 873 | resp.begin() |
| 874 | resp.fp = io.BufferedReader(resp.fp) |
| 875 | self.resp = resp |
| 876 | |
| 877 | |
| 878 | |
| 879 | def test_peek(self): |
| 880 | resp = self.resp |
| 881 | # patch up the buffered peek so that it returns not too much stuff |
| 882 | oldpeek = resp.fp.peek |
| 883 | def mypeek(n=-1): |
| 884 | p = oldpeek(n) |
| 885 | if n >= 0: |
| 886 | return p[:n] |
| 887 | return p[:10] |
| 888 | resp.fp.peek = mypeek |
| 889 | |
| 890 | all = [] |
| 891 | while True: |
| 892 | # try a short peek |
| 893 | p = resp.peek(3) |
| 894 | if p: |
| 895 | self.assertGreater(len(p), 0) |
| 896 | # then unbounded peek |
| 897 | p2 = resp.peek() |
| 898 | self.assertGreaterEqual(len(p2), len(p)) |
| 899 | self.assertTrue(p2.startswith(p)) |
| 900 | next = resp.read(len(p2)) |
| 901 | self.assertEqual(next, p2) |
| 902 | else: |
| 903 | next = resp.read() |
| 904 | self.assertFalse(next) |
| 905 | all.append(next) |
| 906 | if not next: |
| 907 | break |
| 908 | self.assertEqual(b"".join(all), self.lines_expected) |
| 909 | |
| 910 | def test_readline(self): |
| 911 | resp = self.resp |
| 912 | self._verify_readline(self.resp.readline, self.lines_expected) |
| 913 | |
| 914 | def _verify_readline(self, readline, expected): |
| 915 | all = [] |
| 916 | while True: |
| 917 | # short readlines |
| 918 | line = readline(5) |
| 919 | if line and line != b"foo": |
| 920 | if len(line) < 5: |
| 921 | self.assertTrue(line.endswith(b"\n")) |
| 922 | all.append(line) |
| 923 | if not line: |
| 924 | break |
| 925 | self.assertEqual(b"".join(all), expected) |
| 926 | |
| 927 | def test_read1(self): |
| 928 | resp = self.resp |
| 929 | def r(): |
| 930 | res = resp.read1(4) |
| 931 | self.assertLessEqual(len(res), 4) |
| 932 | return res |
| 933 | readliner = Readliner(r) |
| 934 | self._verify_readline(readliner.readline, self.lines_expected) |
| 935 | |
| 936 | def test_read1_unbounded(self): |
| 937 | resp = self.resp |
| 938 | all = [] |
| 939 | while True: |
| 940 | data = resp.read1() |
| 941 | if not data: |
| 942 | break |
| 943 | all.append(data) |
| 944 | self.assertEqual(b"".join(all), self.lines_expected) |
| 945 | |
| 946 | def test_read1_bounded(self): |
| 947 | resp = self.resp |
| 948 | all = [] |
| 949 | while True: |
| 950 | data = resp.read1(10) |
| 951 | if not data: |
| 952 | break |
| 953 | self.assertLessEqual(len(data), 10) |
| 954 | all.append(data) |
| 955 | self.assertEqual(b"".join(all), self.lines_expected) |
| 956 | |
| 957 | def test_read1_0(self): |
| 958 | self.assertEqual(self.resp.read1(0), b"") |
| 959 | |
| 960 | def test_peek_0(self): |
| 961 | p = self.resp.peek(0) |
| 962 | self.assertLessEqual(0, len(p)) |
| 963 | |
| 964 | class ExtendedReadTestChunked(ExtendedReadTest): |
| 965 | """ |
| 966 | Test peek(), read1(), readline() in chunked mode |
| 967 | """ |
| 968 | lines = ( |
| 969 | 'HTTP/1.1 200 OK\r\n' |
| 970 | 'Transfer-Encoding: chunked\r\n\r\n' |
| 971 | 'a\r\n' |
| 972 | 'hello worl\r\n' |
| 973 | '3\r\n' |
| 974 | 'd!\n\r\n' |
| 975 | '9\r\n' |
| 976 | 'and now \n\r\n' |
| 977 | '23\r\n' |
| 978 | 'for something completely different\n\r\n' |
| 979 | '3\r\n' |
| 980 | 'foo\r\n' |
| 981 | '0\r\n' # terminating chunk |
| 982 | '\r\n' # end of trailers |
| 983 | ) |
| 984 | |
| 985 | |
| 986 | class Readliner: |
| 987 | """ |
| 988 | a simple readline class that uses an arbitrary read function and buffering |
| 989 | """ |
| 990 | def __init__(self, readfunc): |
| 991 | self.readfunc = readfunc |
| 992 | self.remainder = b"" |
| 993 | |
| 994 | def readline(self, limit): |
| 995 | data = [] |
| 996 | datalen = 0 |
| 997 | read = self.remainder |
| 998 | try: |
| 999 | while True: |
| 1000 | idx = read.find(b'\n') |
| 1001 | if idx != -1: |
| 1002 | break |
| 1003 | if datalen + len(read) >= limit: |
| 1004 | idx = limit - datalen - 1 |
| 1005 | # read more data |
| 1006 | data.append(read) |
| 1007 | read = self.readfunc() |
| 1008 | if not read: |
| 1009 | idx = 0 #eof condition |
| 1010 | break |
| 1011 | idx += 1 |
| 1012 | data.append(read[:idx]) |
| 1013 | self.remainder = read[idx:] |
| 1014 | return b"".join(data) |
| 1015 | except: |
| 1016 | self.remainder = b"".join(data) |
| 1017 | raise |
| 1018 | |
Berker Peksag | babc688 | 2015-02-20 09:39:38 +0200 | [diff] [blame] | 1019 | |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1020 | class OfflineTest(TestCase): |
Berker Peksag | babc688 | 2015-02-20 09:39:38 +0200 | [diff] [blame] | 1021 | def test_all(self): |
| 1022 | # Documented objects defined in the module should be in __all__ |
| 1023 | expected = {"responses"} # White-list documented dict() object |
| 1024 | # HTTPMessage, parse_headers(), and the HTTP status code constants are |
| 1025 | # intentionally omitted for simplicity |
| 1026 | blacklist = {"HTTPMessage", "parse_headers"} |
| 1027 | for name in dir(client): |
| 1028 | if name in blacklist: |
| 1029 | continue |
| 1030 | module_object = getattr(client, name) |
| 1031 | if getattr(module_object, "__module__", None) == "http.client": |
| 1032 | expected.add(name) |
| 1033 | self.assertCountEqual(client.__all__, expected) |
| 1034 | |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1035 | def test_responses(self): |
Ezio Melotti | b3aedd4 | 2010-11-20 19:04:17 +0000 | [diff] [blame] | 1036 | self.assertEqual(client.responses[client.NOT_FOUND], "Not Found") |
Georg Brandl | 4cbd1e3 | 2006-02-17 22:01:08 +0000 | [diff] [blame] | 1037 | |
Berker Peksag | abbf0f4 | 2015-02-20 14:57:31 +0200 | [diff] [blame] | 1038 | def test_client_constants(self): |
| 1039 | # Make sure we don't break backward compatibility with 3.4 |
| 1040 | expected = [ |
| 1041 | 'CONTINUE', |
| 1042 | 'SWITCHING_PROTOCOLS', |
| 1043 | 'PROCESSING', |
| 1044 | 'OK', |
| 1045 | 'CREATED', |
| 1046 | 'ACCEPTED', |
| 1047 | 'NON_AUTHORITATIVE_INFORMATION', |
| 1048 | 'NO_CONTENT', |
| 1049 | 'RESET_CONTENT', |
| 1050 | 'PARTIAL_CONTENT', |
| 1051 | 'MULTI_STATUS', |
| 1052 | 'IM_USED', |
| 1053 | 'MULTIPLE_CHOICES', |
| 1054 | 'MOVED_PERMANENTLY', |
| 1055 | 'FOUND', |
| 1056 | 'SEE_OTHER', |
| 1057 | 'NOT_MODIFIED', |
| 1058 | 'USE_PROXY', |
| 1059 | 'TEMPORARY_REDIRECT', |
| 1060 | 'BAD_REQUEST', |
| 1061 | 'UNAUTHORIZED', |
| 1062 | 'PAYMENT_REQUIRED', |
| 1063 | 'FORBIDDEN', |
| 1064 | 'NOT_FOUND', |
| 1065 | 'METHOD_NOT_ALLOWED', |
| 1066 | 'NOT_ACCEPTABLE', |
| 1067 | 'PROXY_AUTHENTICATION_REQUIRED', |
| 1068 | 'REQUEST_TIMEOUT', |
| 1069 | 'CONFLICT', |
| 1070 | 'GONE', |
| 1071 | 'LENGTH_REQUIRED', |
| 1072 | 'PRECONDITION_FAILED', |
| 1073 | 'REQUEST_ENTITY_TOO_LARGE', |
| 1074 | 'REQUEST_URI_TOO_LONG', |
| 1075 | 'UNSUPPORTED_MEDIA_TYPE', |
| 1076 | 'REQUESTED_RANGE_NOT_SATISFIABLE', |
| 1077 | 'EXPECTATION_FAILED', |
| 1078 | 'UNPROCESSABLE_ENTITY', |
| 1079 | 'LOCKED', |
| 1080 | 'FAILED_DEPENDENCY', |
| 1081 | 'UPGRADE_REQUIRED', |
| 1082 | 'PRECONDITION_REQUIRED', |
| 1083 | 'TOO_MANY_REQUESTS', |
| 1084 | 'REQUEST_HEADER_FIELDS_TOO_LARGE', |
| 1085 | 'INTERNAL_SERVER_ERROR', |
| 1086 | 'NOT_IMPLEMENTED', |
| 1087 | 'BAD_GATEWAY', |
| 1088 | 'SERVICE_UNAVAILABLE', |
| 1089 | 'GATEWAY_TIMEOUT', |
| 1090 | 'HTTP_VERSION_NOT_SUPPORTED', |
| 1091 | 'INSUFFICIENT_STORAGE', |
| 1092 | 'NOT_EXTENDED', |
| 1093 | 'NETWORK_AUTHENTICATION_REQUIRED', |
| 1094 | ] |
| 1095 | for const in expected: |
| 1096 | with self.subTest(constant=const): |
| 1097 | self.assertTrue(hasattr(client, const)) |
| 1098 | |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 1099 | |
| 1100 | class SourceAddressTest(TestCase): |
| 1101 | def setUp(self): |
| 1102 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1103 | self.port = support.bind_port(self.serv) |
| 1104 | self.source_port = support.find_unused_port() |
Charles-François Natali | 6e20460 | 2014-07-23 19:28:13 +0100 | [diff] [blame] | 1105 | self.serv.listen() |
Gregory P. Smith | b406637 | 2010-01-03 03:28:29 +0000 | [diff] [blame] | 1106 | self.conn = None |
| 1107 | |
| 1108 | def tearDown(self): |
| 1109 | if self.conn: |
| 1110 | self.conn.close() |
| 1111 | self.conn = None |
| 1112 | self.serv.close() |
| 1113 | self.serv = None |
| 1114 | |
| 1115 | def testHTTPConnectionSourceAddress(self): |
| 1116 | self.conn = client.HTTPConnection(HOST, self.port, |
| 1117 | source_address=('', self.source_port)) |
| 1118 | self.conn.connect() |
| 1119 | self.assertEqual(self.conn.sock.getsockname()[1], self.source_port) |
| 1120 | |
| 1121 | @unittest.skipIf(not hasattr(client, 'HTTPSConnection'), |
| 1122 | 'http.client.HTTPSConnection not defined') |
| 1123 | def testHTTPSConnectionSourceAddress(self): |
| 1124 | self.conn = client.HTTPSConnection(HOST, self.port, |
| 1125 | source_address=('', self.source_port)) |
| 1126 | # We don't test anything here other the constructor not barfing as |
| 1127 | # this code doesn't deal with setting up an active running SSL server |
| 1128 | # for an ssl_wrapped connect() to actually return from. |
| 1129 | |
| 1130 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1131 | class TimeoutTest(TestCase): |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 1132 | PORT = None |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1133 | |
| 1134 | def setUp(self): |
| 1135 | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1136 | TimeoutTest.PORT = support.bind_port(self.serv) |
Charles-François Natali | 6e20460 | 2014-07-23 19:28:13 +0100 | [diff] [blame] | 1137 | self.serv.listen() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1138 | |
| 1139 | def tearDown(self): |
| 1140 | self.serv.close() |
| 1141 | self.serv = None |
| 1142 | |
| 1143 | def testTimeoutAttribute(self): |
Jeremy Hylton | 3a38c91 | 2007-08-14 17:08:07 +0000 | [diff] [blame] | 1144 | # This will prove that the timeout gets through HTTPConnection |
| 1145 | # and into the socket. |
| 1146 | |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1147 | # default -- use global socket timeout |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 1148 | self.assertIsNone(socket.getdefaulttimeout()) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1149 | socket.setdefaulttimeout(30) |
| 1150 | try: |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1151 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1152 | httpConn.connect() |
| 1153 | finally: |
| 1154 | socket.setdefaulttimeout(None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1155 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
| 1156 | httpConn.close() |
| 1157 | |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1158 | # no timeout -- do not use global socket default |
Serhiy Storchaka | 25d8aea | 2014-02-08 14:50:08 +0200 | [diff] [blame] | 1159 | self.assertIsNone(socket.getdefaulttimeout()) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1160 | socket.setdefaulttimeout(30) |
| 1161 | try: |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1162 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, |
Christian Heimes | 5e69685 | 2008-04-09 08:37:03 +0000 | [diff] [blame] | 1163 | timeout=None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1164 | httpConn.connect() |
| 1165 | finally: |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1166 | socket.setdefaulttimeout(None) |
| 1167 | self.assertEqual(httpConn.sock.gettimeout(), None) |
| 1168 | httpConn.close() |
| 1169 | |
| 1170 | # a value |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1171 | httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) |
Georg Brandl | f78e02b | 2008-06-10 17:40:04 +0000 | [diff] [blame] | 1172 | httpConn.connect() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1173 | self.assertEqual(httpConn.sock.gettimeout(), 30) |
| 1174 | httpConn.close() |
| 1175 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1176 | |
| 1177 | class HTTPSTest(TestCase): |
| 1178 | |
| 1179 | def setUp(self): |
| 1180 | if not hasattr(client, 'HTTPSConnection'): |
| 1181 | self.skipTest('ssl support required') |
| 1182 | |
| 1183 | def make_server(self, certfile): |
| 1184 | from test.ssl_servers import make_https_server |
Antoine Pitrou | da23259 | 2013-02-05 21:20:51 +0100 | [diff] [blame] | 1185 | return make_https_server(self, certfile=certfile) |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 1186 | |
| 1187 | def test_attributes(self): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1188 | # simple test to check it's storing the timeout |
| 1189 | h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) |
| 1190 | self.assertEqual(h.timeout, 30) |
| 1191 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1192 | def test_networked(self): |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1193 | # Default settings: requires a valid cert from a trusted CA |
| 1194 | import ssl |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1195 | support.requires('network') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1196 | with support.transient_internet('self-signed.pythontest.net'): |
| 1197 | h = client.HTTPSConnection('self-signed.pythontest.net', 443) |
| 1198 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 1199 | h.request('GET', '/') |
| 1200 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 1201 | |
| 1202 | def test_networked_noverification(self): |
| 1203 | # Switch off cert verification |
| 1204 | import ssl |
| 1205 | support.requires('network') |
| 1206 | with support.transient_internet('self-signed.pythontest.net'): |
| 1207 | context = ssl._create_unverified_context() |
| 1208 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, |
| 1209 | context=context) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1210 | h.request('GET', '/') |
| 1211 | resp = h.getresponse() |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1212 | h.close() |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1213 | self.assertIn('nginx', resp.getheader('server')) |
| 1214 | |
Benjamin Peterson | 2615e9e | 2014-11-25 15:16:55 -0600 | [diff] [blame] | 1215 | @support.system_must_validate_cert |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1216 | def test_networked_trusted_by_default_cert(self): |
| 1217 | # Default settings: requires a valid cert from a trusted CA |
| 1218 | support.requires('network') |
| 1219 | with support.transient_internet('www.python.org'): |
| 1220 | h = client.HTTPSConnection('www.python.org', 443) |
| 1221 | h.request('GET', '/') |
| 1222 | resp = h.getresponse() |
| 1223 | content_type = resp.getheader('content-type') |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1224 | h.close() |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1225 | self.assertIn('text/html', content_type) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1226 | |
| 1227 | def test_networked_good_cert(self): |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1228 | # We feed the server's cert as a validating cert |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1229 | import ssl |
| 1230 | support.requires('network') |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1231 | with support.transient_internet('self-signed.pythontest.net'): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1232 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1233 | context.verify_mode = ssl.CERT_REQUIRED |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1234 | context.load_verify_locations(CERT_selfsigned_pythontestdotnet) |
| 1235 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1236 | h.request('GET', '/') |
| 1237 | resp = h.getresponse() |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1238 | server_string = resp.getheader('server') |
Victor Stinner | b389b48 | 2015-02-27 17:47:23 +0100 | [diff] [blame] | 1239 | h.close() |
Georg Brandl | fbaf931 | 2014-11-05 20:37:40 +0100 | [diff] [blame] | 1240 | self.assertIn('nginx', server_string) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1241 | |
| 1242 | def test_networked_bad_cert(self): |
| 1243 | # We feed a "CA" cert that is unrelated to the server's cert |
| 1244 | import ssl |
| 1245 | support.requires('network') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1246 | with support.transient_internet('self-signed.pythontest.net'): |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1247 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1248 | context.verify_mode = ssl.CERT_REQUIRED |
| 1249 | context.load_verify_locations(CERT_localhost) |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1250 | h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context) |
| 1251 | with self.assertRaises(ssl.SSLError) as exc_info: |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1252 | h.request('GET', '/') |
Benjamin Peterson | 4ffb075 | 2014-11-03 14:29:33 -0500 | [diff] [blame] | 1253 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
| 1254 | |
| 1255 | def test_local_unknown_cert(self): |
| 1256 | # The custom cert isn't known to the default trust bundle |
| 1257 | import ssl |
| 1258 | server = self.make_server(CERT_localhost) |
| 1259 | h = client.HTTPSConnection('localhost', server.port) |
| 1260 | with self.assertRaises(ssl.SSLError) as exc_info: |
| 1261 | h.request('GET', '/') |
| 1262 | self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1263 | |
| 1264 | def test_local_good_hostname(self): |
| 1265 | # The (valid) cert validates the HTTP hostname |
| 1266 | import ssl |
Brett Cannon | 252365b | 2011-08-04 22:43:11 -0700 | [diff] [blame] | 1267 | server = self.make_server(CERT_localhost) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1268 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1269 | context.verify_mode = ssl.CERT_REQUIRED |
| 1270 | context.load_verify_locations(CERT_localhost) |
| 1271 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1272 | h.request('GET', '/nonexistent') |
| 1273 | resp = h.getresponse() |
| 1274 | self.assertEqual(resp.status, 404) |
| 1275 | |
| 1276 | def test_local_bad_hostname(self): |
| 1277 | # The (valid) cert doesn't validate the HTTP hostname |
| 1278 | import ssl |
Brett Cannon | 252365b | 2011-08-04 22:43:11 -0700 | [diff] [blame] | 1279 | server = self.make_server(CERT_fakehostname) |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1280 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1281 | context.verify_mode = ssl.CERT_REQUIRED |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1282 | context.check_hostname = True |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1283 | context.load_verify_locations(CERT_fakehostname) |
| 1284 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1285 | with self.assertRaises(ssl.CertificateError): |
| 1286 | h.request('GET', '/') |
| 1287 | # Same with explicit check_hostname=True |
| 1288 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1289 | check_hostname=True) |
| 1290 | with self.assertRaises(ssl.CertificateError): |
| 1291 | h.request('GET', '/') |
| 1292 | # With check_hostname=False, the mismatching is ignored |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1293 | context.check_hostname = False |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1294 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1295 | check_hostname=False) |
| 1296 | h.request('GET', '/nonexistent') |
| 1297 | resp = h.getresponse() |
| 1298 | self.assertEqual(resp.status, 404) |
Benjamin Peterson | a090f01 | 2014-12-07 13:18:25 -0500 | [diff] [blame] | 1299 | # The context's check_hostname setting is used if one isn't passed to |
| 1300 | # HTTPSConnection. |
| 1301 | context.check_hostname = False |
| 1302 | h = client.HTTPSConnection('localhost', server.port, context=context) |
| 1303 | h.request('GET', '/nonexistent') |
| 1304 | self.assertEqual(h.getresponse().status, 404) |
| 1305 | # Passing check_hostname to HTTPSConnection should override the |
| 1306 | # context's setting. |
| 1307 | h = client.HTTPSConnection('localhost', server.port, context=context, |
| 1308 | check_hostname=True) |
| 1309 | with self.assertRaises(ssl.CertificateError): |
| 1310 | h.request('GET', '/') |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1311 | |
Petri Lehtinen | e119c40 | 2011-10-26 21:29:15 +0300 | [diff] [blame] | 1312 | @unittest.skipIf(not hasattr(client, 'HTTPSConnection'), |
| 1313 | 'http.client.HTTPSConnection not available') |
Łukasz Langa | a5a9a9c | 2011-10-18 21:17:39 +0200 | [diff] [blame] | 1314 | def test_host_port(self): |
| 1315 | # Check invalid host_port |
| 1316 | |
| 1317 | for hp in ("www.python.org:abc", "user:password@www.python.org"): |
| 1318 | self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp) |
| 1319 | |
| 1320 | for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", |
| 1321 | "fe80::207:e9ff:fe9b", 8000), |
| 1322 | ("www.python.org:443", "www.python.org", 443), |
| 1323 | ("www.python.org:", "www.python.org", 443), |
| 1324 | ("www.python.org", "www.python.org", 443), |
| 1325 | ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443), |
| 1326 | ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", |
| 1327 | 443)): |
| 1328 | c = client.HTTPSConnection(hp) |
| 1329 | self.assertEqual(h, c.host) |
| 1330 | self.assertEqual(p, c.port) |
| 1331 | |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 1332 | |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1333 | class RequestBodyTest(TestCase): |
| 1334 | """Test cases where a request includes a message body.""" |
| 1335 | |
| 1336 | def setUp(self): |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1337 | self.conn = client.HTTPConnection('example.com') |
Jeremy Hylton | 636950f | 2009-03-28 04:34:21 +0000 | [diff] [blame] | 1338 | self.conn.sock = self.sock = FakeSocket("") |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1339 | self.conn.sock = self.sock |
| 1340 | |
| 1341 | def get_headers_and_fp(self): |
| 1342 | f = io.BytesIO(self.sock.data) |
| 1343 | f.readline() # read the request line |
Jeremy Hylton | 7c1692d | 2009-03-27 21:31:03 +0000 | [diff] [blame] | 1344 | message = client.parse_headers(f) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1345 | return message, f |
| 1346 | |
| 1347 | def test_manual_content_length(self): |
| 1348 | # Set an incorrect content-length so that we can verify that |
| 1349 | # it will not be over-ridden by the library. |
| 1350 | self.conn.request("PUT", "/url", "body", |
| 1351 | {"Content-Length": "42"}) |
| 1352 | message, f = self.get_headers_and_fp() |
| 1353 | self.assertEqual("42", message.get("content-length")) |
| 1354 | self.assertEqual(4, len(f.read())) |
| 1355 | |
| 1356 | def test_ascii_body(self): |
| 1357 | self.conn.request("PUT", "/url", "body") |
| 1358 | message, f = self.get_headers_and_fp() |
| 1359 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1360 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1361 | self.assertEqual("4", message.get("content-length")) |
| 1362 | self.assertEqual(b'body', f.read()) |
| 1363 | |
| 1364 | def test_latin1_body(self): |
| 1365 | self.conn.request("PUT", "/url", "body\xc1") |
| 1366 | message, f = self.get_headers_and_fp() |
| 1367 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1368 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1369 | self.assertEqual("5", message.get("content-length")) |
| 1370 | self.assertEqual(b'body\xc1', f.read()) |
| 1371 | |
| 1372 | def test_bytes_body(self): |
| 1373 | self.conn.request("PUT", "/url", b"body\xc1") |
| 1374 | message, f = self.get_headers_and_fp() |
| 1375 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1376 | self.assertIsNone(message.get_charset()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1377 | self.assertEqual("5", message.get("content-length")) |
| 1378 | self.assertEqual(b'body\xc1', f.read()) |
| 1379 | |
| 1380 | def test_file_body(self): |
Victor Stinner | 18d15cb | 2011-09-21 01:09:04 +0200 | [diff] [blame] | 1381 | self.addCleanup(support.unlink, support.TESTFN) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1382 | with open(support.TESTFN, "w") as f: |
| 1383 | f.write("body") |
| 1384 | with open(support.TESTFN) as f: |
| 1385 | self.conn.request("PUT", "/url", f) |
| 1386 | message, f = self.get_headers_and_fp() |
| 1387 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1388 | self.assertIsNone(message.get_charset()) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1389 | self.assertEqual("4", message.get("content-length")) |
| 1390 | self.assertEqual(b'body', f.read()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1391 | |
| 1392 | def test_binary_file_body(self): |
Victor Stinner | 18d15cb | 2011-09-21 01:09:04 +0200 | [diff] [blame] | 1393 | self.addCleanup(support.unlink, support.TESTFN) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1394 | with open(support.TESTFN, "wb") as f: |
| 1395 | f.write(b"body\xc1") |
| 1396 | with open(support.TESTFN, "rb") as f: |
| 1397 | self.conn.request("PUT", "/url", f) |
| 1398 | message, f = self.get_headers_and_fp() |
| 1399 | self.assertEqual("text/plain", message.get_content_type()) |
Raymond Hettinger | 7beae8a | 2011-01-06 05:34:17 +0000 | [diff] [blame] | 1400 | self.assertIsNone(message.get_charset()) |
Brett Cannon | 77b7de6 | 2010-10-29 23:31:11 +0000 | [diff] [blame] | 1401 | self.assertEqual("5", message.get("content-length")) |
| 1402 | self.assertEqual(b'body\xc1', f.read()) |
Jeremy Hylton | 236654b | 2009-03-27 20:24:34 +0000 | [diff] [blame] | 1403 | |
Senthil Kumaran | 9f8dc44 | 2010-08-02 11:04:58 +0000 | [diff] [blame] | 1404 | |
| 1405 | class HTTPResponseTest(TestCase): |
| 1406 | |
| 1407 | def setUp(self): |
| 1408 | body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \ |
| 1409 | second-value\r\n\r\nText" |
| 1410 | sock = FakeSocket(body) |
| 1411 | self.resp = client.HTTPResponse(sock) |
| 1412 | self.resp.begin() |
| 1413 | |
| 1414 | def test_getting_header(self): |
| 1415 | header = self.resp.getheader('My-Header') |
| 1416 | self.assertEqual(header, 'first-value, second-value') |
| 1417 | |
| 1418 | header = self.resp.getheader('My-Header', 'some default') |
| 1419 | self.assertEqual(header, 'first-value, second-value') |
| 1420 | |
| 1421 | def test_getting_nonexistent_header_with_string_default(self): |
| 1422 | header = self.resp.getheader('No-Such-Header', 'default-value') |
| 1423 | self.assertEqual(header, 'default-value') |
| 1424 | |
| 1425 | def test_getting_nonexistent_header_with_iterable_default(self): |
| 1426 | header = self.resp.getheader('No-Such-Header', ['default', 'values']) |
| 1427 | self.assertEqual(header, 'default, values') |
| 1428 | |
| 1429 | header = self.resp.getheader('No-Such-Header', ('default', 'values')) |
| 1430 | self.assertEqual(header, 'default, values') |
| 1431 | |
| 1432 | def test_getting_nonexistent_header_without_default(self): |
| 1433 | header = self.resp.getheader('No-Such-Header') |
| 1434 | self.assertEqual(header, None) |
| 1435 | |
| 1436 | def test_getting_header_defaultint(self): |
| 1437 | header = self.resp.getheader('No-Such-Header',default=42) |
| 1438 | self.assertEqual(header, 42) |
| 1439 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1440 | class TunnelTests(TestCase): |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1441 | def setUp(self): |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1442 | response_text = ( |
| 1443 | 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT |
| 1444 | 'HTTP/1.1 200 OK\r\n' # Reply to HEAD |
| 1445 | 'Content-Length: 42\r\n\r\n' |
| 1446 | ) |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1447 | self.host = 'proxy.com' |
| 1448 | self.conn = client.HTTPConnection(self.host) |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1449 | self.conn._create_connection = self._create_connection(response_text) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1450 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1451 | def tearDown(self): |
| 1452 | self.conn.close() |
| 1453 | |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1454 | def _create_connection(self, response_text): |
| 1455 | def create_connection(address, timeout=None, source_address=None): |
| 1456 | return FakeSocket(response_text, host=address[0], port=address[1]) |
| 1457 | return create_connection |
| 1458 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1459 | def test_set_tunnel_host_port_headers(self): |
| 1460 | tunnel_host = 'destination.com' |
| 1461 | tunnel_port = 8888 |
| 1462 | tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'} |
| 1463 | self.conn.set_tunnel(tunnel_host, port=tunnel_port, |
| 1464 | headers=tunnel_headers) |
| 1465 | self.conn.request('HEAD', '/', '') |
| 1466 | self.assertEqual(self.conn.sock.host, self.host) |
| 1467 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1468 | self.assertEqual(self.conn._tunnel_host, tunnel_host) |
| 1469 | self.assertEqual(self.conn._tunnel_port, tunnel_port) |
| 1470 | self.assertEqual(self.conn._tunnel_headers, tunnel_headers) |
| 1471 | |
| 1472 | def test_disallow_set_tunnel_after_connect(self): |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1473 | # Once connected, we shouldn't be able to tunnel anymore |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1474 | self.conn.connect() |
| 1475 | self.assertRaises(RuntimeError, self.conn.set_tunnel, |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1476 | 'destination.com') |
| 1477 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1478 | def test_connect_with_tunnel(self): |
| 1479 | self.conn.set_tunnel('destination.com') |
| 1480 | self.conn.request('HEAD', '/', '') |
| 1481 | self.assertEqual(self.conn.sock.host, self.host) |
| 1482 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1483 | self.assertIn(b'CONNECT destination.com', self.conn.sock.data) |
Serhiy Storchaka | 4ac7ed9 | 2014-12-12 09:29:15 +0200 | [diff] [blame] | 1484 | # issue22095 |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1485 | self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data) |
| 1486 | self.assertIn(b'Host: destination.com', self.conn.sock.data) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1487 | |
| 1488 | # This test should be removed when CONNECT gets the HTTP/1.1 blessing |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1489 | self.assertNotIn(b'Host: proxy.com', self.conn.sock.data) |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1490 | |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1491 | def test_connect_put_request(self): |
| 1492 | self.conn.set_tunnel('destination.com') |
| 1493 | self.conn.request('PUT', '/', '') |
| 1494 | self.assertEqual(self.conn.sock.host, self.host) |
| 1495 | self.assertEqual(self.conn.sock.port, client.HTTP_PORT) |
| 1496 | self.assertIn(b'CONNECT destination.com', self.conn.sock.data) |
| 1497 | self.assertIn(b'Host: destination.com', self.conn.sock.data) |
| 1498 | |
Berker Peksag | ab53ab0 | 2015-02-03 12:22:11 +0200 | [diff] [blame] | 1499 | def test_tunnel_debuglog(self): |
| 1500 | expected_header = 'X-Dummy: 1' |
| 1501 | response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header) |
| 1502 | |
| 1503 | self.conn.set_debuglevel(1) |
| 1504 | self.conn._create_connection = self._create_connection(response_text) |
| 1505 | self.conn.set_tunnel('destination.com') |
| 1506 | |
| 1507 | with support.captured_stdout() as output: |
| 1508 | self.conn.request('PUT', '/', '') |
| 1509 | lines = output.getvalue().splitlines() |
| 1510 | self.assertIn('header: {}'.format(expected_header), lines) |
Senthil Kumaran | e6cc701 | 2015-01-24 19:24:59 -0800 | [diff] [blame] | 1511 | |
Senthil Kumaran | 9da047b | 2014-04-14 13:07:56 -0400 | [diff] [blame] | 1512 | |
Benjamin Peterson | 9566de1 | 2014-12-13 16:13:24 -0500 | [diff] [blame] | 1513 | @support.reap_threads |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 1514 | def test_main(verbose=None): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1515 | support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1516 | HTTPSTest, RequestBodyTest, SourceAddressTest, |
Kristján Valur Jónsson | 8e5d0ca | 2014-03-19 10:07:26 +0000 | [diff] [blame] | 1517 | HTTPResponseTest, ExtendedReadTest, |
Senthil Kumaran | 166214c | 2014-04-14 13:10:05 -0400 | [diff] [blame] | 1518 | ExtendedReadTestChunked, TunnelTests) |
Jeremy Hylton | 2c17825 | 2004-08-07 16:28:14 +0000 | [diff] [blame] | 1519 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1520 | if __name__ == '__main__': |
| 1521 | test_main() |